C# NullReferenceException

Hello,
Why is this?

 itemGameObject.transform.GetChild(1).GetComponent<RectTransform>().localPosition = new Vector2(GameObject.FindGameObjectWithTag("MainInventory").GetComponent<Inventory>().positionNumberX, GameObject.FindGameObjectWithTag("MainInventory").GetComponent<Inventory>().positionNumberY);

Giving:
NullReferenceException: Object reference not set to an instance of an object
CraftResultSlot.Start () (at Assets/InventoryMaster/Scripts/CraftSystem/CraftResultSlot.cs:27)
I am using this asset:

That line is extremely long, and poorly written.
A null reference exception is thrown when you try to access members of an object that does not have a value (null)

You can test which object is null yourself by refactoring your code:

Debug.Log("itemGameObject is " + (itemGameObject == null ? "null" : "not null"));

var secondChild = itemGameObject.transform.GetChild(1); //if you're getting the child at index 1, you're getting the second child.
Debug.Log("secondChild is " + (firstChild == null ? "null" : "not null"));

var rectTransform = firstChild as RectTransform; //you don't need to get the rect transform component. RectTransform is a subclass of transform. If it can be cast, then it exists.
Debug.Log("rectTransform is " + (rectTransform == null ? "null" : "not null"));

var mainInventory = GameObject.FindObjectWithTag("MainInventory"); // don't do this more than once. FindObjectWithTag is an expensive operation. Cache the gameObject once found.
Debug.Log("mainInventory is " + (mainInventory == null ? "null" : "not null"));

var inventory = mainInventory.GetComponent<Inventory>();
Debug.Log("inventory is " + (inventory == null ? "null" : "not null"));

//Once you've figured out which object is null and have rectified the problem you can set your localPosition.
rectTransform.localPosition = new Vector2(inventory.positionNumberX, inventory.positionNumberY);
2 Likes

Thanks. That works but now it gives error for:

itemGameObject.SetActive(false);

If the gameObject is null, you wont be able to set it as inactive because it doesn’t exist, right?

I suggest you take some programming tutorials!

Coming to the forums for help is fine, but our help will be a lot more useful to you if you have some foundational skills to work off of.

1 Like

Okay, thanks i will.