I have two scripts ItemSpawnController and a Script CollectItems. The ItemSpawnController has a field
public bool TreasureSpawned { set; private set; } = false; this field is set by some functions while runtime.
The CollectItem class is referencing the ItemSpawnController class and i am trying to access the Field. But while runtime i am getting Null Reference Exception.
public class CollectItems : MonoBehaviour
{
public ItemSpawnManager spawnManager;
void Update()
{
if (spawnManager.TreasureSpawned == false)
{
//add 15 points to player
}
}
}
ItemSpawnManager Class
public class ItemSpawnManager : MonoBehaviour
{
//properties
public bool TreasureSpawned { get; private set; } = false;
.
.
.
}
Let me compliment you first on thoroughly working through the steps above. Everything above shows that you have this field defined in at least one place.
Are you sure that is actually the place that’s crashing? I suspect not. You could have more than one of these inadvertently! OR something else may later be nulling it.
i began with commenting out every line one by one and found that the problem is with the first line “items[1]”. then i looked on the the Prefab apple which was referenced here, and what i saw surprised me.
the apple prefab had also a script the CollectItems script attached to it. which removed the reference. see screenshot below.
The Idea was at the beginning to implement Collect functionally in the prefabs. but i moved away from it because prefabs can only use dynamic ways to find the SpawnManager script. after Instantiating.
after removing the collectscript everything is working fine.
so commenting out code section by section definitely helps. Thanks Kurt-Dekker!