r/programminghelp • • Sep 18 '20

C# C# Unity: Checking if an object is null before trying to use it, and the object still throws a MissingReferenceException?

Like the title says I'm working with Unity and C#. In unity I'm trying to have objects keep track of neighboring objects in a list, and when a neighboring object is deleted to remove them from the list. I keep having if(circuitObject == null) return; in the beginning of my functions that deal with these neighboring objects but it doesn't seem to be working. I still get MissingReferenceExceptions.

Before I delete each object I ask all of it's neighbors "Delete this object from your list, then make sure your list doesn't have any null references" through the following code:

public bool RemoveSelf()
    {
        if (!canDelete) return false;

        foreach (CircuitItem ci in NeighborList)
        {
            ci.RemoveFlow(this); // Remove from the other neighbors neighborList
        }
        
        Destroy(gameObject); // Delete this GameObject
        return true;
    }

public virtual bool RemoveFlow(CircuitItem ci) {
        // I was having issues where List.Remove(GameObject) would sometimes remove the wrong GameObject
        if (ci != null)
        {
            List<CircuitItem> tempList = new List<CircuitItem>();

            for (int i = 0; i < NeighborList.Count; i++)
            {
                if (NeighborList[i] != ci && NeighborList[i] != null)
                {
                    tempList.Add(NeighborList[i]);
                }
            }
            
            NeighborList = tempList;

            return true;
        }
        return false;
}

This seems super inefficient but using List.Remove(object) was often removing the wrong object. I also have a solution that kept track of each index of objects in each list but that created a lot of overhead. The error comes in during the DiscoverFlow(CircuitItem) function which is called anytime an object is initialized, it will ask each of it's neighbors to try and discover it

public int DiscoverFlow(CircuitItem input)
    {
        if (input == null) return badFlowIndex; // I check if it's null
        
        if (flowChecking.Contains(input) && input.FlowCheck.Contains(this) && flowChecking.IndexOf(input) != badFlowIndex)
        {
            return flowChecking.IndexOf(input);
        }
        
        Navigation.Direction dir = Navigation.DirectionBetween(transform.position, input.transform.position); // RIGHT HERE I KEEP GETTING THE ERROR THAT IT'S NULL
        
        //Rest of the function
}

That last actual code line specifically at input.transform.position I get the error:"Object of type CircuitItem has been destroy but you are still trying to access it. Your script should check if it's null or you should not destroy it"But I am checking if it's null. It doesn't get caught by my conditional, so why? Is there something I don't understand about how Unity destroy's things? Is there something I don't understand about C#'s null value? How does it keep skipping the if(input == null) return badFlowIndes; but still throw a statement that it's null?

Second question: in the RemoveSelf() function, I inconsistently run into issues where the object is deleted before it's removed from other object Lists, I tried to do while(ci.NeighborList.Contains(this)) ci.RemoveFlow(this); but that creates an infinite loop. I can't figure out what is wrong with my RemoveFlow function. It looks like it should be removing the object properly.

Edit: messed up 2 variable names

4 Upvotes

2 comments sorted by

1

u/amoliski Sep 18 '20

You say:

List<CircuitItem> tempList = new List<CircuitItem>(); 
...
NeighborList.Add(flowChecking[i]); 
...
NeighborList = tempList; 

You never add anything to tempList, though- did you mean to do tempList.Add(...)?

Can you place a logging line or a breakpoint to see what 'input' is before you call .transform.position on it?

2

u/tremblinggigan Sep 19 '20

Sorry, I was changing flowChecking to NeighborList so that it's easier to read for someone who doesn't have the whole project and I messed that line up, thank you for catching it.

I did do the log line and it turns out I have the cause of the bug backwards, again thank you. The object the function belongs to is null...I don't know how I'm pulling that off.

My logline was:
Debug.Log("input is: " + input + " and I am " + this);

And right before I replicated the error it printed out:
input is: Pipe(Clone) and I am null