Trouble with Stack's Contains() method?

I’m trying an example from my book where objects that enter a trigger are thrown in a stack “HitStack”. Then the stack is copied to an array “HitList” (after the array is reinitialized.)

Game compiles and runs without error/warning, but as soon as I move a 3D object into the trigger, I get a NullReferenceException:

NullReferenceException: Object reference not set to an instance of an object
HitTrigger.OnTriggerEnter (UnityEngine.Collider other) (at Assets/HitTrigger.cs:15)

…debugger shows the error taking place at line: 16 where Contains() is used.

using UnityEngine;
using System.Collections;

public class HitTrigger : MonoBehaviour {
    public GameObject [] HitList;
    public Stack HitStack;

    void Start () {
    }

    void Update () {
    }

    void OnTriggerEnter (Collider other) {
        Debug.Log ("Made contact with " + other.gameObject);
        if (!HitStack.Contains(other.gameObject)) {
            Debug.Log("Doesn't exist in HitStack... adding now!");
            HitStack.Push(other.gameObject);
            HitList = new GameObject[HitStack.Count];
            HitStack.CopyTo(HitList, 0);
        }
    }
}

Where is HitStack initialized? A null error means that reference is empty. You probably wanted:

void Start() {
    HitStack = new Stack();
}

Thanks. Why do I have to initialize a stack, but not array?

uh, you have to initialize all objects before using them, including arrays. Can you post some code that looks like the array isn’t initialized before you use it?

Sorry, I meant, why do I have to use: HitStack = new Stack()
Otherwise HitStack returns nulll?

Until you assign a reference to an object, that reference will be empty (“null” in programmer-speak). I’m still wondering this:

#include <iostream>

using namespace std;

int main()
{
    int myArray[5];

    for (int i = 0; i < 5; i++)
    {
    myArray[i] = i;
    }

    cout << myArray[3] << endl;
    return 0;
}

okay, that’s C++ code. I suppose we never specifically said this, but around here it’s kinda implied that you’re talking about C# or UnityScript code (since this is the Unity forum). So let me amend my query to “can you post some Unity code that demonstrates an array being used without being initialized?” That said, typing “int myArray[5]” is initializing an array; C++ just has bizarre syntax for initializing an array.

Half joking around… Turns out my C++ threw me off, I was used to declaring arrays in that fashion.

Also, I also just noticed the code at line 19.

… And to answer your question about arrays. No I cannot. Now that I think about it.

Still learning and a little confused, thanks for your help!:slight_smile: