1

I have a class for lists called UniqueListWithActions<T> with the constructor method

    public UniqueListWithActions(List<T> _list)
    {
        list = _list;
    }

list is declared as

    public List<T> list;

but in the method ClearNulls, the debug returns "null and False".

public void ClearNulls()
{
    for (int i = list.Count - 1; i >= 0; i--)
    {
        Debug.Log(list[i] + " and " + (list[i] == null));
        if (list[i] == null)
        {
            list.RemoveAt(i);
        }
    }
}

I set up the following, put it on an empty gameobject, put two other empty game objects into the list through the inspector, destroyed one so the reference was missing, and then hit escape and it still comes up "null and False".

public class ListTest : MonoBehaviour
{
    public UniqueListWithActions<GameObject> uniqueList = new UniqueListWithActions<GameObject>(new List<GameObject>());
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            uniqueList.ClearNulls();
        }
    }
}

I don't understand how it can be null enough that "null" is what's returned in the debug but not "null" enough that list[i] != null. It's not called the same frame the object is destroyed since i do it by hand. How can I clear all the null objects in the list if null isn't null?

New contributor
Isaac Bargamian is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2

2 Answers 2

4

Unity shows destroyed objects as "null" , but they aren’t real C# nulls.
Unity’s (==) operator only works if the compiler knows the type is UnityEngine.Object.
In your class, "T" isn’t constrained, so C# uses a normal comparison that’s why list[i] == null returns false.

New contributor
Mikloo is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

3

try a look at

try https://discussions.unity.com/t/how-to-check-if-a-gameobject-is-being-destroyed/822565/7

where


        if (object.ReferenceEquals(obj, null)) return true;

        if (obj is UnityEngine.Object) return (obj as UnityEngine.Object) == null;

        return false;
    }

is the a common test, although it does describe how unity sets items for destruction so its null and not null .. (Anyone have flash backs to hittchikers guide to the galaxy game for tea and no tea?)

1 Comment

fyi if you already use is you can directly include the type conversion as in if (obj is UnityEngine.Object unityObject) return unityObject == null;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.