简体   繁体   English

试图在两点之间进行 lerp 但得到 NullReferenceException [unity]

[英]Trying to lerp between two point but get NullReferenceException [ unity]

I'm trying to lerp between two points in my script but i get NullReferenceException我试图在我的脚本中的两点之间进行 lerp 但我得到 NullReferenceException
here is the code:这是代码:

    Transform  endPos;
    float speed;
 void Start()
    {
       endPos.position = new Vector3(0, -1, 1);

    }
 void  Update()
    {
    transform.position = Vector3.Lerp(transform.position, endPos.position, speed * Time.deltaTime);
    }     

Interesting thing is that when i set the transform to public and set it in editor it works.有趣的是,当我将转换设置为 public 并在编辑器中设置它时,它可以工作。
I even tried to use it through creating a gameObject and set the postion through there but no luck.我什至试图通过创建一个游戏对象来使用它并通过那里设置位置,但没有运气。
so how can i do it through script and not editor?那么我如何通过脚本而不是编辑器来做到这一点?
Thanks.谢谢。

It is happening because your endPos transform is null when you try to set its position.这是因为当您尝试设置其位置时,您的endPos转换为空。 Use Vector3 instead of transform.使用Vector3而不是变换。 Edit your code like this像这样编辑你的代码

    Vector3 endPos;
    float speed;

    void Start()
    {
       endPos = new Vector3(0, -1, 1);    
    }

    void Update()
    {
       transform.position = Vector3.Lerp(transform.position, endPos, speed * Time.deltaTime);
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM