Object reference not set to an instance of an object
So i have a shop script for my game and have assigned everything and i keep getting this problem:
NullReferenceException: Object reference not set to an instance of an object AddItem.BuyItem () (at Assets/Scripts/Shop/AddItem.cs:25) UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:154) UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:637) UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:773) UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:52) UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36) UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45) UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50) 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:261) UnityEngine.EventSystems.EventSystem:Update()
This is my script:
public float requiredGold;
private PlayerStats thePS;
public Transform itemToDeactivate;
public Transform itemToActivate;
// Use this for initialization
void Start () {
thePS = GetComponent<PlayerStats>();
}
// Update is called once per frame
void Update () {
}
public void BuyItem ()
{
if (thePS.currentGold >= requiredGold)
{
itemToDeactivate.gameObject.SetActive(false);
itemToActivate.gameObject.SetActive(true);
}
}
Can anybody please help me?
Are you sure the PlayerStats script is attached to the same game object this Shop script is?
Answer by Commoble · Jan 30, 2018 at 09:21 PM
thePS, ItemToDeactivate, or ItemToActivate hasn't been initialized (or possibly all three). Your error message tells you which line of the file it's happening in. Make sure that the fields you've exposed to the Inspector all have stuff in them, and if you're using GetComponent make sure that your object actually has the relevant component attached to it.