Okay, so this is making me feel completely dumb.
I’m making a game in which you can collect things. They have to respawn when the player loses a life.
I have two C# classes. One “Umpire” class that manages things that should be maintained and managed throughout gameplay, and a “Collectible” class, which I’m having a few other classes (“Coin” and “Upgrade”) inherit from.
The Umpire class is attached to a GameObject named “Umpire” in my scene, and my scene contains “Coin” and “Upgrade” objects.
In the Umpire class, I’m making a List of Collectibles that contains all Collectible objects that have been collected during the player’s current life. I want to add to this from the Collectible class upon collision with the player.
The weird thing however, is that this list stays null when I try to add to it, throwing me a null reference exception! Now, this might just be my exhaustion catching up to me, but I just don’t see what I’m doing wrong.
I’ve tried public and private (with getters and setters), static and non-static (because I just want one list, but there will only ever be one umpire object, so either should be fine), but nothing makes a difference.
I even added a useless integer to check whether I could assign and retrieve that, and I can, so there must be something particular with lists going on…
The Umpire class:
using System.Collections.Generic;
using UnityEngine;
public class Umpire : MonoBehaviour
{
public List<Collectible> collectedDuringThisLife;
public int indicator;
private void Awake()
{
collectedDuringThisLife = new List<Collectible>(); //List of collected coins. Stays null??
indicator = 6;
//DontDestroyOnLoad(transform.gameObject);
}
void Update()
{
/*
*/
}
}
The Collectible class
(inherited from by Coin and Upgrade):
using UnityEngine;
public class Collectible : MonoBehaviour {
GameObject umpire;
char letter;
private void Start()
{
umpire = GameObject.Find("Umpire"); // Get the Umpire GameObject from the Scene
Debug.Log(umpire.GetComponent<Umpire>().indicator); // Check if the integer is assigned.
//It is.
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player") // If the player touches the collectible
{
Debug.Log(umpire.GetComponent<Umpire>().collectedDuringThisLife);//.Add(this);
//Not adding right now, just checking if exists. Gives nullreference exception either way.
this.gameObject.SetActive(false); // Make it disappear
}
}
}
So yeah, I’m probably missing something obvious, but I’m at the end of my wits here. Any insight would be greatly appreciated!