- Home /
Store Instantiated Object script reference
I'm instantiating an enemy object and then want to get it's script reference and store it in a list, but I keep getting NullReferenceException: Object reference not set to an instance of an object Though it successfully gets the component, as the test function runs correctly.
private List<Unit> enemyTeam;
Vector3 enemyPosition = new Vector3(5 + x, 1 - 1.2f*i, 0f);
GameObject enemy = enemies[Random.Range (0, enemies.Length)];
GameObject enemyInstance = Instantiate(enemy, enemyPosition, Quaternion.identity) as GameObject;
Unit enemyUnit = enemyInstance.GetComponent<Unit> ();
enemyUnit.test ();
enemyTeam.Add (enemyUnit);
The error is produced by the last line. What I'm doing wrong? Sorry if this is a stupid mitake, I'm very new to Unity, I would also love to find a mentor :)
It seems the error was caused because the enemyTeam List was private. How could it be so?
Use comments and not answers when you don't have an answer!!! Converted to comment.
Answer by OncaLupe · Dec 29, 2015 at 02:16 AM
The error is because your list is not yet initialized.
Initialize during creation:
private List<Unit> enemyTeam = new List<Unit>();
Or during run time:
enemyTeam = new List<Unit>();