Search Unity

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

Discussion in 'Editor & General Support' started by HitherWings23, Jan 26, 2021.

  1. HitherWings23

    HitherWings23

    Joined:
    Jan 14, 2021
    Posts:
    1
    Hi,

    I keep receiving this exception when i run the following code. It says the error is coming on line 30. The code still runs perfectly but the error messages are very annoying. Please help!

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class WayCont : MonoBehaviour
    {
    public List<Transform> waypoints = new List<Transform>();
    private Transform targetWaypoint;
    private int targetWaypointIndex = 0;
    private float minDistance = 1.0f;
    private int lastWaypointIndex;

    private float movementSpeed = 3.0f;
    private float rotationSpeed = 2.0f;
    private float distance;

    // Start is called before the first frame update
    void Start()
    {
    lastWaypointIndex = waypoints.Count - 1;
    targetWaypoint = waypoints[targetWaypointIndex];
    }

    // Update is called once per frame
    void Update()
    {
    float movementStep = movementSpeed * Time.deltaTime;
    float rotationStep = rotationSpeed * Time.deltaTime;

    Vector3 directionToTarget = targetWaypoint.position - transform.position;
    Quaternion rotationToTarget = Quaternion.LookRotation(directionToTarget);

    transform.rotation = Quaternion.Slerp(transform.rotation, rotationToTarget, rotationStep);

    float distance = Vector3.Distance(transform.position, targetWaypoint.position);
    checkDistance(distance);

    transform.position = Vector3.MoveTowards(transform.position, targetWaypoint.position, movementStep);



    }

    void checkDistance(float currentDistance)
    {
    if(currentDistance <= minDistance)
    {
    targetWaypointIndex++;
    updateTarget();
    }
    }

    void updateTarget()
    {
    if (targetWaypointIndex > lastWaypointIndex)
    {
    targetWaypointIndex = 0;
    }
    targetWaypoint = waypoints[targetWaypointIndex];
    }
    }