I am very new to C#, so forgive me if this is obvious.
I am following the steps in this tutorial and have run into a problem on step six. The error it gives is this: The error it gives is this:
UnityEngine.Component' does not contain a definition for `velocity' and no extension method `velocity' of type `UnityEngine.Component' could be found. Are you missing an assembly reference?'
Here is the code:
using UnityEngine;
using System.Collections;
public class RobotController : MonoBehaviour {
//This will be our maximum speed as we will always be multiplying by 1
public float maxSpeed = 2f;
//a boolean value to represent whether we are facing left or not
bool facingLeft = true;
//a value to represent our Animator
Animator anim;
// Use this for initialization
void Start () {
//set anim to our animator
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate () {
float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys
//move our Players rigidbody
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
//set our speed
anim.SetFloat ("Speed",Mathf.Abs (move));
//if we are moving left but not facing left flip, and vice versa
if (move < 0 && !facingLeft) {
Flip ();
} else if (move > 0 && facingLeft) {
Flip ();
}
}
//flip if needed
void Flip(){
facingLeft = !facingLeft;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
The error is on line 23:
rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);
You just create a rigidbody object in the start function,
If you are using a 2D animation the use the following code,
rigidbody2D
used to be a variable inherited from Component whichMonoBehaviour
is inherits. It is now deprecated.Now, you have to declare it and initialize it with
GetComponent<Rigidbody>();
just like you did for the Animator(anim
) variable in theStart()
function. Also, to not confuse yourself with the old variable, I suggest that you renamerigidbody2D
to something else. In the example code below, I will rename it torigid2D
and declare it.If you don't rename it, you might get a warning that says: