- Home /
Search for an object by name null reference exception
I am trying to check a list for an object by name. I came across this method:
foo.Find(function (x : GameObject) x.name.Contains(refObj.name)))
the list I have is my list of items in an inventory. The items in the inventory can be withdrawn or deleted at any time.
The problem with this code is that it throws a null reference exception EACH time something is removed or destroyed from the inventory.
Js is all I use. I don't do C#
How do I correctly check if the object is null so I can stop null reference exceptions?
// this does NOT work
if( foo.Find(function (x : GameObject) x.name.Contains(refObj.name)) != null)
I'm just trying to find out how to correctly prevent exception errors with this method. Please dont offer alternative methods or get into WHY do I think I need to use this method. Thanks
Answer by TranceDreams · Aug 17, 2020 at 02:47 AM
Removing the object from the list before destroying is the solution. ie:
foo.Remove(x);
foo.Destroy(x);