【问题标题】:Rigidbody: NullReferenceException: Object reference not set to an instance of an object刚体:NullReferenceException:对象引用未设置为对象的实例
【发布时间】:2022-10-18 23:05:36
【问题描述】:
Rigidbody2D rb;
    private Vector2 startingPosition;
    private Vector2 targetPosition;
    
    void start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        //if (rb != null)
        //{
        //    Debug.Log("no rb forund");
        //}
        startingPosition = rb.position;
        playerBoundary = new Boundary(playerBoundaryHolder.GetChild(0).position.y, playerBoundaryHolder.GetChild(1).position.y, playerBoundaryHolder.GetChild(2).position.x, playerBoundaryHolder.GetChild(3).position.x);
        puckBoundary = new Boundary(puckBoundaryHolder.GetChild(0).position.y, puckBoundaryHolder.GetChild(1).position.y, puckBoundaryHolder.GetChild(2).position.x, puckBoundaryHolder.GetChild(3).position.x);
    }
    private void FixedUpdate()
    {

        //rb = GetComponent<Rigidbody2D>();
        if (rb == null)
        {
            Debug.Log("no found");
        }
        float movementSpeed;
       
        //check if the puck is outside the AiBoundary
        if (puck.position.y < puckBoundary.Down)
        {
            movementSpeed = maxMovementSpeed * Random.Range(0.1f, 0.3f);
            //only move in x axis
            targetPosition = new Vector2(Mathf.Clamp(puck.position.x, playerBoundary.Left, playerBoundary.Right),startingPosition.y);
        }
        else
        {
            movementSpeed = Random.Range(maxMovementSpeed * 0.4f, maxMovementSpeed);
            targetPosition = new Vector2(Mathf.Clamp(puck.position.x, playerBoundary.Left, playerBoundary.Right), Mathf.Clamp(puck.position.y, playerBoundary.Down, playerBoundary.Up));
            
        }
        rb.MovePosition(Vector2.MoveTowards(rb.position, targetPosition,
                movementSpeed * Time.fixedDeltaTime));
    }

}

这是 AI 脚本,unity 不断给出刚体错误。我也尝试过 debug.log 。

【问题讨论】:

  • 为什么这个标签是c++
  • Unity3d 不是用 C++ 编程的。
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如它目前所写的那样,很难准确地说出你在问什么。
  • 你能附上这个脚本的游戏对象的截图吗?

标签: scripting nullreferenceexception rigid-bodies


【解决方案1】:

由于输出表明您有一个空引用,请检查您是否已在检查器中填写了所有变量。

【讨论】:

  • 或其他原因导致问题..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2020-11-17
  • 1970-01-01
相关资源
最近更新 更多