ToArray causes an unassigned reference exception

this is my code:

IEnumerable<GameObject> temp = itemObj.items.OrderBy(itm => (int)itm.GetComponent<IItem>().id);
temp.ToArray();

it works without the ToArray, but with it, it gives an error on the first line:

“UnassignedReferenceException: The variable items of ItemsObject has not been assigned.”

itemObj is a scriptable object, items is an array of GameObjects.

items is assigned. how could trying to convert temp to an array cause items to be unassigned?

so the problem was in the anonymous function (itm => (int)itm.GetComponent().id)

some of my items that it was looking at were null.

Google “deferred execution lambda c#”

Until you reference temp, it really isn’t executing the assignment. So when you say it works without the ToArray(), that’s because it hasn’t done anything yet. Try doing a foreach with temp and it will likely fail. If you do it “old school” without lamda, you will likely find the issue.

EDIT - looks like you figured it out while I was typing.

2 Likes