0

This is my Code:

GameObject[] targets;
List<Transform> transformlist;

void Start () {
    targets = GameObject.FindGameObjectsWithTag("target");
    Debug.Log(targets.Length);
    foreach (GameObject obj in targets)
    {
        Transform transform = obj.transform;
        transformlist.Add(transform);
    }
    Debug.Log(transformlist.Count);

}

I need to do this as I want my camera to point at the nearest gameobject, which I have written later in my script. It doesn't matter what I try (array or list) it still says

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

HOWEVER, my first "Debug.Log(targets.length)" returns with 5400, the actual number of gameobjects with the "target" tag, so I know it is getting that far at least.

Is it something complicated or am I just being stupid? Many Thanks for all who help.

Virb
  • 1,639
  • 1
  • 16
  • 25
Alex Hobbs
  • 11
  • 1

1 Answers1

2

Before foreach:

transformlist = new List<Transform>();

Inside foreach:

Transform transform = obj.transform;
transformlist.Add(transform);
001
  • 13,291
  • 5
  • 35
  • 66
Adam
  • 490
  • 7
  • 21