I am making a multiplayer game in which the characters can change scenes. I have items scattered in different scenes which the player can pick up and add to his inventory. The items have an 'AddItem' script attached to them. If the player is in the first scene and picks up the item, it is added to the inventory, however when the player changes the scene and picks up an item in that scene (which is using same script), it throws null reference error. Here is the script:
public class AddItem : MonoBehaviour
{
public Item item;
DialogueConditions dc;
private GameObject player;
private void Start()
{
player = GameObject.Find("Engineer");
dc = player.GetComponent<DialogueConditions>();
}
void pickUp()
{
Debug.Log("Picking up : " + item.name);
HasBriefDoc();
bool itemPickedUp = Inventory.instance.Add(item);
if(itemPickedUp == true)
{
Destroy(gameObject);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
pickUp();
}
}
public void HasBriefDoc()
{
if (item == null)
{
dc.hasBrief = false;
}
else if (item.name == "Brief Doc")
{
dc.hasBrief = true;
}
else
{
dc.hasBrief = false; //throws null reference
}
}
}
After debugging, I found out that after scene change, the object 'dc' is assigned with null reference in the Start() method. I also tried initializing it with FindObjectOfType<DialogueConditions>();
and adding the start code to the Awake()
method, but the problem still persists. The only way it is working is when I drop the 'dc' object and directly use static variables, which is something I do not prefer.