PDA

View Full Version : Unity C# for noobs



Blocko
12-25-2015, 04:13 PM
If you are reading this you want to learn c#. Let's start!

-------------------------------------------------------------------------

Lets think we have done player movement script, and we want tell the unity how fast player walks and we want modify it in inspector

First we need create float, float can used for speed.

This is how is gonna looks like:

----------------------------------------------------------------------------------------------
Public float Speed;
----------------------------------------------------------------------------------------------

Public means that you can modify "speed" in other scripts.
If you dont tell to unity is the component private or public unity makes it automatically private.
----------------------------------------------------------------------------------------------

Lets look that code strip again:

Public float speed
^
First you need to tell is the component private or public

--------------------------------------------------------------------

Public float speed
^
Then we need to tell what kind of component we are making.

---------------------------------------------------------------------
Public float speed
^
And last we name it to "speed" (you can name it whatever you want)

---------------------------------------------------------------------
Now we have the speed, and it's zero because we didn't tell to unity what how fast its gonna be.
It's easy to fix.

-----------------------------------------------------------------------

Public float speed = 10;

----------------------------------------------------------------------

Now unity knows the speed, we can use this value in our movement

---------------------------------------------------------------------

if(Input.GetKey (KeyCode.D))
{
transform.Translate(Vector2.right * speed * Time.deltaTime);

}

---------------------------------------------------------------------

MyLegGuy
12-25-2015, 07:39 PM
Don't forget that public variables can be changed in the inspector. And you should also describe what a float is.

Also this place is dead. You shouldn't bother posting here.
http://forum.unity3d.com/

|ThyLuigi|
12-30-2015, 09:25 PM
Code please.

MyLegGuy
12-31-2015, 12:06 AM
Code please.
It's all right there.
Just put it together.
I think this would work:


using UnityEngine;
using System.Collections;

public class Movement: MonoBehaviour {
Public float speed = 10.5;
void Update() {
if(Input.GetKey (KeyCode.D))
{
transform.Translate(Vector2.right * speed * Time.deltaTime);

}
}
}

Blocko
12-31-2015, 09:55 AM
It's all right there.
Just put it together.
I think this would work:


using UnityEngine;
using System.Collections;

public class Movement: MonoBehaviour {
Public float speed = 10.5;
void Update() {
if(Input.GetKey (KeyCode.D))
{
transform.Translate(Vector2.right * speed * Time.deltaTime);

}
}
}


It does but it moves you only right, do same with keycode.w