Why does this Instantiate give a Null Reference Exception?

Hey Comm-unity,
I am working on a project, and I can’t seem to get it to stop returning a null reference exception. Here’s the code:

Slide s = new Slide();
			GameObject g = GameObject.Instantiate(ButtonPrefab, new Vector3(slides[slides.Count - 1].button.transform.position.x + xpos, slides[slides.Count - 1].button.transform.position.y + ypos, 0.0f), Quaternion.identity) as GameObject;
			s.button = g.GetComponent<Button>();
			s.button.transform.SetParent(ButtonParent.transform);
			slides.Add (s);

And here’s the error:

NullReferenceException: Object reference not set to an instance of an object
Manager.Add () (at Assets/Scripts/Manager.cs:110)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:137)
UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:601)
UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:743)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
UnityEngine.EventSystems.EventSystem:Update()

And it claims that the error is on the line that says:

s.button = g.GetComponent<Button>();

Thank you in advance for your help!

  • Tiger27

Hello!

Your case is explicit.

If the error is on the line:

s.button = g.GetComponent<Button>();

The null object is either s or g.

It would be surprising that s is null.

I would bet on g, if ButtonPrefab is wrong or null.