Search Unity

NullReferenceException: Object reference not set to an instance of an object pickUp.Start ()

Discussion in 'Scripting' started by Razzy1199, Jan 27, 2020.

  1. Razzy1199

    Razzy1199

    Joined:
    Jan 25, 2020
    Posts:
    6
    Hello! I have a error in my 2D game :
    NullReferenceException: Object reference not set to an instance of an object
    pickUp.Start () (at Assets/Scripts/pickUp.cs:12)
    and I've tried everything to fix it, i just can't figure it out please help me!

    My script :


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class pickUp : MonoBehaviour
    6. {
    7.     private Inventory inventory;
    8.     public GameObject itemButton;
    9.  
    10.       private void Start()
    11.     {
    12.         inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<Inventory>();
    13.     }
    14.  
    15.     void OnTriggerEnter2D(Collider2D other)
    16.     {
    17.         if (other.CompareTag("Player"))
    18.         {
    19.             for (int i = 0; i < inventory.slots.Length; i++)
    20.             {
    21.                 if(inventory.isFull[i] == false)
    22.                 {
    23.                     //can be added to inventory
    24.                     inventory.isFull[i] = true;
    25.                     Instantiate(itemButton, inventory.slots[i].transform, false);
    26.                     Destroy(gameObject);
    27.                     break;
    28.                 }
    29.             }
    30.         }
    31.  
    32.     }
    33. }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    NullReferenceErrors are some of the easiest to solve. They simply mean something has no value. In this case, you are probably missing something tagged as "Player" or it can't find your "Player" since it's occuring on line 12.
     
  3. Razzy1199

    Razzy1199

    Joined:
    Jan 25, 2020
    Posts:
    6
    Thank you! As you said it was very easy to solve just had to add a tag to my player. :)