Daniel Minder
Daniel Minder

Reputation: 29

Unity - Accessing GameObjects saved via DontDestroyOnLoad()

I am trying to create a unique script that will allow me to easily set up what enemies to load once BattleScene starts. To do so, I went for a array of GameObjects, assigned objects I want to spawn on the second scene and placed DontDestroyOnLoad() on it. The result is that the object passes to a next scene and has it's references attached correctly (at least showing up in Inspctor) but once I try to get the GameObjects stored in this Array from a script on a Second Scene I get a null reference.

I've spent like whole afternoon google'ing and searching for answer, but didn't find out (maybe because of my lack of experience and understanding on how things work in Unity). So I am simply asking for help - not only for solution, but also a explanation what am I doing wrong and how it works.

The code for setting up a Array:

public class BattleEnemyInfo : MonoBehaviour
{

public GameObject[] enemyList;

public void Start()
{
    enemyList = GetComponentInParent<Patrol>().UnitList;
}


}

Screenshot of this object's Inspector:

enter image description here

Note that it has a Tag assigned!

Hierarchy on SecondScene:

enter image description here

Unity error:

enter image description here

And the code I am trying to call the Array:

EnemyPrefab = GameObject.FindWithTag("EnemyInfo");
    enemyListBattleReady = EnemyPrefab.GetComponent<BattleEnemyInfo>().enemyList;

Upvotes: 0

Views: 1091

Answers (1)

Kevin Harper
Kevin Harper

Reputation: 76

Get Component will result null if the game object you are trying to get it from is not active. Turn the game object on.

Upvotes: 1

Related Questions