What have i done here not working?

trying to get one object to pick another random object position from an array and move towards it but having a problem, script looks simple but keep getting errors, bit stuck

using UnityEngine;
using System.Collections;

public class TOTARGET : MonoBehaviour {
    public GameObject[] targets;
    public float speed;



    private GameObject target;


    void Start(){

   

    Transform spawnPoint = target[Random.Range(0, targets.Length)].transform;
    transform.LookAt(spawnPoint);
    }



    void Update() {

        target = spawnPoint.position;




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

On line 17 you try to get a random value from target, but your array is called targets

updated code a bit, now getting “object reference not sett o an instance of an object” error at line 33

using UnityEngine;
using System.Collections;

public class TOTARGET : MonoBehaviour {
    public GameObject[] targets;
    public float speed;

    private GameObject spawnPoint;



    private GameObject target;


    void Start(){

  

    Transform spawnPoint = targets[Random.Range(0, targets.Length)].transform;

    }



    void Update() {

  




        float step = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, spawnPoint.transform.position, step);
    }
}

The error tells you exactly what’s wrong, try to figure out what it’s telling you.

Oh my goodness! It’s ALWAYS the same answer, ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

Cant see what can be missing or unasigned at line 33, transform position is the gameobject position the script is atached to, move towards transform position is the current position of this gameobject and spawnpoint transform position is the position of the gameobject picked grom the array, so how can anything be unasigned?

Edit… Just realised now i changed the target to targets i left the private gameobject target in the script ooops my bad

1 Like

still getting the same error, i can not get this right i have tried to see what is wrong but just not registering with me, we are not all code masters using unity, all objects have a reference allready so why the error? can anyone give me a sensible answer and not just critisize please thank you.

edit: caused by Transform on the random checker now fixed, still does not make sense though as the transform was asigned!!!

Delete Transform in the start method. Just spawnPoint = …

You have two variables with the name spawnPoint declared. One is a GameObject type global to your class and another is a local Transform only living in the start method.

1 Like