Search code examples
unity-game-engine3dplatform

Unity - Moving Platform from Point A to Point B


I am trying to make a game in Unity and I am stuck in a part where I am trying to move a platform from Point A to Point B.

The error I get is:

NullReferenceException: Object reference not set to an instance of an object MovingPlatform.Update () (at Assets/Scripts/MovingPlatform.cs:30)

The Source Code is:

public class MovingPlatform : MonoBehaviour
{
    [SerializeField]
    private Transform pointA, pointB;

    private float speed = 1.0f;

    private Transform target;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position == pointA.position)
        {
            target = pointB;
        }
        else if (transform.position == pointB.position)
        {
            target = pointA;
        }
        
        transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);

    }
}

What should I do?

Because the platform is not moving at all.


Solution

  • The error tells you whats wrong. In line 30 of your script you have a reference somewhere which is null (hence NullReferenceException) and you try to do something with this (e.g. accessing attributes). I guess its target.position from

    transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    

    when your if-statements dont trigger. You should add target = pointB; in Start() to have target properly initialized (i assume you want start out moving to pointB).