- Home /
Destroy() not working
One of the games I'm working on to get a feel for Unity is a Missile Command game. One where the player would be able to click on the screen to get the point where the missiles would fly to and then explode. The problem I'm having at the moment is that my missiles aren't exploding when they reach the point. The missiles constantly move/translate towards the point even after reaching it. My scene is set up so that I have a collider volume catching the points for the missile destinations. A ray would shoot out of the camera, hit the collider, then a missile would move towards that point the ray hit on the collider.
In my C# code below, which is placed on the missiles, I have it set up so that if the missile is fired from any of the 3 missile launching buildings it would take the spawn point and destination point and compare the two. This is supposed to determine which "if" check to use to see if the missile has reached the point or not. If the missile isn't at the point, the "Alive()" method is executed but if the missile is at the point or exceeded the position of the destination then the "Dead()" method is executed. This is what's supposed to happen but isn't for some reason. One final thing, due to me setting up my scene a little wrong, the "z-axis" is acting as the "x-axis" in the code below. Any help is appreciated.
using UnityEngine; using System.Collections; using System;
public class PlayerMissile : MonoBehaviour {
#region Fields public float speed; private Transform MissileTransform; private Vector3 MissilePosition; private Vector3 Destination; private Vector3 Spawn; #endregion
void Start() { MissileTransform = transform; MissilePosition = transform.position; Destination = Camera.main.GetComponent<Controls>().missileDeathLoc; Spawn = Camera.main.GetComponent<Controls>().missileSpawn; }
//Update is called once per frame void Update() { if (Spawn.z > Destination.z) { if (MissilePosition.z > Destination.z && MissilePosition.y < Destination.y) { Alive(); } if (MissilePosition.z <= Destination.z && MissilePosition.y >= Destination.y) { Dead(); } } if (Spawn.z < Destination.z) { if (MissilePosition.z < Destination.z && MissilePosition.y < Destination.y) { Alive(); } if (MissilePosition.z >= Destination.z && MissilePosition.y >= Destination.y) { Dead(); } } }
void Alive() { //looks at the destination and moves towards it MissileTransform.LookAt(Destination); MissileTransform.Translate(Vector3.forward (speed Time.deltaTime)); }
void Dead() { Debug.Log("Death triggered"); //deletes the missile if at the destination and subtracts the number of missiles onscreen Camera.main.GetComponent<Controls>().missileCount--; Destroy(gameObject); }
}