I have an array of game objects that I’m trying to search through to get a reference to the one named but I keep getting returned a null and I’m not sure why. I’m a beginner at programming so please temper your answer toward a beginner’s understanding, many thanks.
using System.Linq;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ItemManager : MonoBehaviour
}
public Item[] Items;
void Start ()
{
for (int i = 0; i < Items.Length; i++)
{
Debug.Log ("Item Name: " + Items*.Name);*
//gets a reference to the item with this name
public Item GetItemByName(string itemName)
{
return Items.FirstOrDefault(item => item.Name == itemName);
}
}
GetItemsByName () is called by another script when the object the other script is attached to is destroyed using OnDestroy ().
Unless you have other code initializing the Items array it will always be null. This would cause a NullPointerException (NPE) in Start() on line 14 and in GetItemByName() on line 22.
You could fix this by initializing Items to some default starting size:
public class ItemManager : MonoBehaviour
{
public Item[] Items = new Item[5]
...
If you’re using Items as a variable size container I might recommend using System.Collections.Generic.List (List<T> Class (System.Collections.Generic) | Microsoft Learn) instead.
Your code would change to something like
using System.Linq;
using UnityEngine;
using System.Collections.Generic;
public class ItemManager : MonoBehaviour
{
// the main difference from using an array is the declaration and initialization
// of Items here.
public List<Item> Items = new List<Item>();
void Start ()
{
for (int i = 0; i < Items.Count; i++)
{
Debug.Log ("Item Name: " + Items*.Name);*
}
}
// gets a reference to the item with this name
public Item GetItemByName(string itemName)
{
Debug.Log ("inside GetItemByName looking for: " + itemName);
return Items.FirstOrDefault(item => item.Name == itemName);
}
}