当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《UnityError:UnityEngine.Component'不包含`velocity'的定义》经验,为你挑选了1个好方法。



1> Programmer..:

rigidbody2D以前是继承自Component的变量MonoBehaviour.它已被弃用.

现在,您必须声明它并初始化它,GetComponent();就像您animStart()函数中的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;
    }
}

推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有