- Home /
Making the enemy shoot only when player is alive
I'm making a pretty simple bullethell game, and I would like the enemy to stop shooting when my player dies(it is active when alive, and not active when dead). I don't know where I fail in the code. It gives me a NullReferenceException when my player dies (gets deactivated).
var enemyLaser : GameObject; var fireFreq : float; var projectileSpeed:float = 0.0; private var lastShot : float;
function Update () {
if (Time.time > lastShot + fireFreq){
Fire();
}
}
function Fire() {
lastShot = Time.time;
var player = GameObject.Find("player");
if (player.active){
var shoot = Instantiate(enemyLaser,transform.position,transform.rotation);
shoot.rigidbody.velocity = (player.transform.position - transform.position).normalized * projectileSpeed;
}
}
Well... What line is the null reference co$$anonymous$$g from? is it when you attempt to file the GameObject 'player'?
Have you not attached a prefab to enemyLaser in the inspector?
It comes from Line 15. The game seems to work fine, until they hit me and my character dies. NullReferenceException comes then. The script does exactly what I want until that point (they will shoot at the player's position). And yes, I have attached the prefab.
Without that if statement, the game is completely playable, but I want them to stop shooting while I'm respawning.
Answer by Dave-Carlile · Feb 12, 2013 at 02:22 PM
If you're destroying or disabling the player
when they die, then GameObject.Find
wil no longer find that object. So after this line...
var player = GameObject.Find("player");
The player
variable will be null, then when you reference the player.active
property...
if (player.active)
you'll get a null reference exception. You can fix it by changing your if
statement...
if (player != null && player.active)
{
... your stuff here ...
}
So it will only execute the code inside if
when the player
object is found.
Thanks, that indeed fixed the problem. I didn't realize GameObject.Find cannot find disabled objects.
Answer by asasababoon · Feb 12, 2013 at 03:34 PM
when deactivated it cant acces it. you could solve it by having an boolean in the player's script. and checking that value (if its alive or not)
Your answer
Follow this Question
Related Questions
How do I stop an immediate collision with all objects from ocuring at the entry of game mode? 0 Answers
how can i get a pause screen to work 0 Answers
If you disable a gameobject, does an InvokeRepeating loop end or pause? 3 Answers
[SOLVED] How I can detect deleted gameobject 1 Answer
How to determine the direction of an object to the player. 1 Answer