I’m kinda new with Unity, especially with C# and I am trying to make my character to walk, but my script doesn’t work! In the Console it says that the object has to be referenced. How do I do that? On line 10 I just wrote rigidbody2D, because everywhere it is written like that.
public class PlayerController : MonoBehaviour {
public int speed = 10;
void Update() {
if (Input.GetKeyDown (“a”)) {
Rigidbody2D.velocity = new Vector2(-speed, 0);
}
}
}
Alright, so your problem comes from the fact that you are referencing the class rather than an object.
Make a ‘public Rigidbody2D rigidbody2D;’ under your speed variable. In the Inspector, you’ll notice that a box appears on this script. Drag and drop the object with the Rigidbody2D component onto this slot. Then decapitalize the the Rigidbody2D, and you’ll be good to go
Tom’s method should work, here is an alternative to get the component using code:
public class PlayerController : MonoBehaviour {
public int speed = 10;
private Rigidbody2D myRigidbody;
// called by Unity once when the game first loads
private void Awake() {
// gets the Rigidbody2D component on this game object
// or returns null if there isn't one
myRigidbody = GetComponent<Rigidbody2D>();
}
// called by Unity once per frame
private void Update() {
if(Input.GetKeyDown("a")) {
myRigidbody.velocity = new Vector2(-speed, 0);
}
}
}