- Home /
Object reference not set to an instance of an object
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
Answer by Spikeh · Jun 10, 2013 at 05:37 PM
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! $$anonymous$$aybe you need to use otherObject ins$$anonymous$$d of this.gameObject? Depends what the script is applied to I suppose?
Your answer
![](https://koobas.hobune.stream/wayback/20220613103917im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Problem with passing object to another script. 1 Answer
How to add to a list excluding certain items 1 Answer
Switching Target during Target Lock 1 Answer