Object reference not set to an instance of an object (73090)

Hi there! I’m trying to make a simple script, that will add a gameobject to my list, when the player collides with it and presses the use key. However I keep getting the “Object reference not set to an instance of an object” error. It points to the second script, line 22. Any help?

First script PlayerInventory.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PlayerInventory : MonoBehaviour {
	
	public List<GameObject> myInventory;
	
	void Start()
	{	    		
		myInventory = new List<GameObject>();
	}
		
	public void AddToInventory(GameObject newItem)
	{
		myInventory.Add (newItem);
		Debug.Log ("Added");
	}
	
}

Second script GameObjectToInventory.cs

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameObjectToInventory : MonoBehaviour {	
		
	private PlayerInventory playerInventory;	

	void OnTriggerStay(Collider otherObject) 
	{	
		
		if(Input.GetButtonDown("Use")){			
				PlayerInventory playerInventory = GetComponent<PlayerInventory>();			
				playerInventory.AddToInventory(this.gameObject);
				Destroy (this.gameObject);
				}
	}	
}

You don't have any line 22 on any of these two scripts.

Do you really have the script PlayerInventory attached to the game object containing the second script ?

@Angry Armadillo try commenting the Destroy (this.gameObject) and see what happens

1 Answer

1

There’s no line 22 anywhere, but I can tell you that your second script has a syntax error. You have tried to instantiate playerInventory twice. Only one line needs changing:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class GameObjectToInventory : MonoBehaviour {    
 
    private PlayerInventory playerInventory;   
 
 
    void OnTriggerStay(Collider otherObject) 
    {  
 
       if(Input.GetButtonDown("Use")){      
          playerInventory = GetComponent<PlayerInventory>();
          playerInventory.AddToInventory(this.gameObject);
          Destroy (this.gameObject);
      }
    }  
}

Ah, silly me, I formatted the code so the actual line for the error is 15. But after fixing the syntax error unity still throws me the Object reference error.

I'm very new to Unity scripting, though I'm a c# vet - so I'm not entirely sure what everything does yet! Maybe you need to use otherObject instead of this.gameObject? Depends what the script is applied to I suppose?