Rigidbody: NullReferenceException: Object reference not set to an instance of an object

Viewed 22
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));
    }

}

this is AI script and the unity is continuously giving rigidbody error. I have tried debug.log as well.

1 Answers

since the output says that you have an empty reference, check if you have filled all variables in the inspector.

Related