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

Viewed 35

//My code is here I am currently designing a tower defense game in unity and have some Enemy AI. Enemy should go from waypoint to waypoint I added enemy script to enemy object. How can i fix this?

using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 10f;

    private Transform target;
    private int wavepointIndex = 0;

    void Start()
    {
        target = Waypoints.points[0];

    }
    void Update()
    {
        
        Vector3 dir = target.position - transform.position; //Enemy.cs:19
        
        transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);

        if(Vector3.Distance(transform.position, target.position) <= 0.4f)
        {
            GetNextWaypoint();
        }
        void GetNextWaypoint()
        {
            if(wavepointIndex >= Waypoints.points.Length - 1)
            {
                Destroy(gameObject);
                return;
            }
            wavepointIndex++;
            target = Waypoints.points[wavepointIndex];
        }
         
    }
}

//also Waypoints class here. I am trying to go from waypoint to waypoint.


using UnityEngine;

public class Waypoints : MonoBehaviour
{
    public static Transform[] points;

    private void Awake()
    {
        points = new Transform[transform.childCount];
        for (int i = 0; i < points.Length; i++)
        {
            points[i] = transform.GetChild(i);

        }
    }
}
0 Answers
Related