- Home /
Destroy happens immediately
I'm currently working on a Starfox-ish game. I've managed to get quite far today, as I've managed to make an enemy fly towards the player. What I want to happen is that once an enemy flies within a certain range of the player, it will fly over the player and then self destruct. This is a behaviour I've called "disengage".
At first I was uncertain how to make the enemy fly over the player (because midair collissions with every enemy would be stupid), then I created an actual prefab which is a child to the players plane, which the enemies try to fly in to.
However, once I wrote the code, I wasn't certain, but I thought it was targeting the "disengage target" straight away. Once I added the self destrct, however, I realised that the enemy plane self destructs immediately. It seems to bypass the timer, as it gets destroyed on frame 1, even if I set the timer to ludicrously large numbers, and the disengage distance to ludicrously small distances.
Anyways, here's the code:
using UnityEngine;
using System.Collections;
public class EnemyFighterScript : MonoBehaviour {
public float interceptvelocity = 10.0f ;
public Transform Player;
public float distance;
public Transform target;
public Transform disengagetarget;
public float disengagedistance;
public bool disengage;
public float timer;
// Use this for initialization
void Start () {
disengage = false;
}
// Update is called once per frame
void Update () {
distance =Vector3.Distance(transform.position,target.position);
if (distance<disengagedistance){
disengage=true;
}
if (disengage=false){
transform.LookAt (Player);
transform.position += transform.forward * interceptvelocity * Time.deltaTime;
}
if (disengage=true) {
//makes enemy fly away and prepare self destruct after reaching proximity to player
transform.LookAt (disengagetarget);
transform.position += transform.forward * interceptvelocity * Time.deltaTime;
timer =- Time.deltaTime;
}
if(timer <= 1){
//destroys NPC once it passes player
Destroy(gameObject);
}
}
}
Are you sure that 'timer' is getting assigned a value in the Inspector. If you did not, then the initial value will be 0.0. Note there is an optional second parameter for Destory() which is the time in the future you want the object to be destroyed. So you could use this form of Destory() and avoid the timer code.
Answer by AlucardJay · Aug 02, 2014 at 09:45 PM
not sure about your problem, but you have incorrect conditional operators at line 25 and line 29
if (disengage=false)
should be
if (disengage==false)
== is equal to
Your answer
Follow this Question
Related Questions
hi guys, i need help 1 Answer
Hiding Texture2D after a sec 1 Answer
Destroy when out of range issue 0 Answers
Distance destroy object 3 Answers
Creating more objects the closer you get 0 Answers