I have checked almost all related questions on the web and have not found the answer yet.
I instantiate an Enemy prefab mid-game and I want the Player to access the script attached to the instantiated Enemy object. Weirdly, I get a Null Reference Exception sometimes, not always. But I need it to work 100% of the time. This is the Player’s script where the error comes from:
var enemyObject : GameObject;
var enemyControllerScript : EnemyController;
var enemyHasEntered : boolean;
function Update()
{
//Enemy object sets enemyHasEntered true in its Start()
if(enemyHasEntered)
{
enemyObject = GameObject.FindWithTag("Enemy");
if(enemyObject != null)
{
enemyControllerScript= enemyObject.GetComponent(EnemyController);
}
//enemyHasEntered = false;
//I would ideally want to execute this section only once
//so repeated FindWithTag wont affect performance.
}
if(Input.GetButtonDown("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(bullet, bulletSpawn.position, Quaternion.identity);
audio.Play();
if(enemyObject != null)
{
enemyControllerScript.SlowMotionEffect();
//This is where I keep getting Null Reference Exception error whenever player fires.
//I cannot access the SlowMotionEffect()of enemy script if FindWithTag fails.
}
}
}