rigidbody2D
以前是继承自Component的变量MonoBehaviour
.它已被弃用.
现在,您必须声明它并初始化它,GetComponent
就像您anim
对Start()
函数中的Animator()变量所做的那样.另外,为了不让自己与旧变量混淆,我建议你重命名rigidbody2D
为其他东西.在下面的示例代码中,我将重命名为rigid2D
并声明它.
如果您不重命名,可能会收到一条警告:
严重性代码描述项目文件行抑制状态警告CS0108'RobotController.rigidbody2D'隐藏继承的成员'Component.rigidbody2D'.如果要隐藏,请使用new关键字.
public class RobotController: MonoBehaviour { 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; //Declare rigid2D Rigidbody rigid2D; // Use this for initialization void Start() { //set anim to our animator anim = GetComponent(); //Initialize rigid2D rigid2D = GetComponent (); } // 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 rigid2D.velocity = new Vector3(move * maxSpeed, rigid2D.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; } }