- Home /
got null reference when trying to access script from instantiate object
hi, so what i want to do is access game script (EnemyScript) that are attached to an instantiated game object. I have attached the script to the original game object, This is the the script (EnemyManager) to spawn the enemy game object and also get the script component from instantiated game object
public class EnemyManager : MonoBehaviour
{
public GameObject zombear;
public GameObject temp;
public GameObject[] activeEnemy = new GameObject[10];//Maximum 10 enemy exist in the game
public int count;
private void Start()
{
count = 0;
}
private void Update()
{
if(TheManager.instance.GetGameStateManager().CurrentPhase == GameStateManager.GamePhase.EnemyPhase)
{
if (activeEnemy[0] != null)
{
for (int i = 0; i < count; i++)
{
if(activeEnemy[count].GetComponent<EnemyScript>())
activeEnemy[count].GetComponent<EnemyScript>().EnemyAction();
else
TheManager.instance.GetCanvasManagerStatus().logUpdate("Script not detected");
}
}
else
TheManager.instance.GetCanvasManagerStatus().logUpdate("No enemy");
}
}
public void spawnZombear(Transform coordinates)
{
temp = Instantiate(zombear, new Vector3(coordinates.position.x, 0.1f, coordinates.position.z), Quaternion.identity);
activeEnemy[count] = temp;
count++;
}
}
i've debug it and it got the error on the activeEnemy[count].GetComponent() what is wrong??
Answer by toddisarockstar · Oct 15, 2017 at 04:29 PM
you are not checking your array for null before you look for the script!!! you have these lines in the wrong order. the check for null should be inside the loop. it should look like this:
for (int i = 0; i < count; i++)
{ if (activeEnemy[i] != null)
{
also looks like you are trying to page through your list of enemies. you are using the "count" variable for an index instead of "i". i think you want to use "i" in your array brackets when saying activeEnemy[i] in your loop
oops my bad, you are right, thank you for the answer, it works :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612141111im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
I have never seen a null reference exception like this one! 1 Answer
Instance is null only in playmode? 1 Answer
Checking if object intersects? 1 Answer
Null Reference Exception transform position y 2 Answers
Issue with photon instantiate 0 Answers