Accessing Field Property from other script is not working

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.

CollectItems Class

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;
.
.
.

}

7903321--1006999--Hierarchy.JPG

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.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

wow your approach is very nice,

i actually isolated the failure step by step and found finally the solution.

here is what i found:

in ItemsSpawnManager class i was Instantiating couple of objects and saving them in an array. like this.

        //spawn three items
        items[1] = Instantiate(toSpawnedItems[apple], spawnPosition[left].position, spawnPosition[left].rotation);
        items[2] = Instantiate(toSpawnedItems[cherry], spawnPosition[right].position, spawnPosition[right].rotation);
       items[3] = Instantiate(toSpawnedItems[cake], spawnPosition[middle].position, spawnPosition[middle].rotation);

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!

7903444--1007020--apple.JPG

1 Like