Unity Error:UnityEngine.Component'不包含`velocity'的定义

时间:2017-01-15 03:12:14

标签: c# unity3d unity5 unity3d-2dtools

我对C#很新,所以如果这很明显,请原谅我。

我正在执行this tutorial中的步骤,并在第六步遇到问题。它给出的错误是:它给出的错误是:

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?'

以下是代码:

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;
}
}

错误在第23行:

rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y);

2 个答案:

答案 0 :(得分:9)

public class Color { public byte Red { get; private set; } public byte Green { get; private set; } public byte Blue { get; private set; } public byte Alpha { get; private set; } public Color(byte red, byte green, byte blue, byte alpha) { this.Red = red; this.Green = green; this.Blue = blue; this.Alpha = alpha; } } Color color = new Color(100, 100, 100, 255); byte redValue = color.Red; color.Red = 0; // Error, cannot set value outside the class. 曾经是从继承rigidbody2D的Component继承的变量。它已被弃用。

现在,您必须声明它并使用MonoBehaviour初始化它,就像您对GetComponent<Rigidbody>();函数中的Animator(anim)变量所做的那样。另外,为了不让自己与旧变量混淆,我建议您将Start()重命名为其他内容。在下面的示例代码中,我将其重命名为rigidbody2D并声明它。

如果您不重命名,可能会收到一条警告:

  

严重级代码描述项目文件行抑制状态   警告CS0108'RobotController.rigidbody2D'隐藏继承的成员   'Component.rigidbody2D'。如果想要隐藏,请使用new关键字。

rigid2D

答案 1 :(得分:0)

您只需在start函数中创建一个刚体对象,

Rigidbody rigidbody = GetComponent<Rigidbody>();

如果您使用的是2D动画,请使用以下代码,

Rigidbody2D rigidbody = GetComponent<Rigidbody2D>();