0

i have problem with this, i create the code when player hit the object the Key variable will increase but in unity it show NullRefrenceException on the console can someone help me to figure it out with this one?

Here is my code Key.cs

public class Key : MonoBehaviour
{
    public int key;

    public Text keyText;

    void Start()
    {
        key = 0;
    }
    void Update()
    {
        keyText.text = "Key: " + key.ToString();
    }

}

GetKey.cs

{
    public int KeyBonus = 1;
    private Key kunci;


    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag == "Player")
        {
            kunci = col.gameObject.GetComponent<Key>();

            //Add Key
            kunci.key += KeyBonus;


            Destroy(this.gameObject);
        }


    }
}
NullReferenceException: Object reference not set to an instance of an object
Key.Update () (at Assets/Script/Key.cs:18)
NullReferenceException: Object reference not set to an instance of an object
GetKey.OnTriggerEnter2D (UnityEngine.Collider2D col) (at Assets/Script/GetKey.cs:18)

1 Answers1

1

The keyText variable is not set, meaning you will throw a null reference exception. Make sure you set you variable within your inspector. If you want to avoid the null reference exception can wrap your code in:

if(keyText != null)

However I would not advise that as then you dont know whether the variable is set.

Branden
  • 337
  • 1
  • 14