- Home /
[SOLVE] Target lock missile script - how to make it keep searching for new target
So I got this script from this forum, thanks to DexRobinson (he made it).
So I'm using his script, and it works perfectly. The problem is that once the target of the missiles are gone, they will just travel forever. I want them to keep searching for a new target... I instantiate 5 missiles at once.
using UnityEngine;
using System.Collections;
public class Missle : MonoBehaviour {
public string searchTag;
private GameObject closetMissle;
private Transform target;
public GameObject missileExpObject;
void Start()
{
closetMissle = FindClosestEnemy();
if(closetMissle)
target = closetMissle.transform;
}
void Update()
{
transform.LookAt(target);
transform.Translate(Vector3.forward * 5.0f * Time.deltaTime);
}
GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag(searchTag);
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach(GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if(curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
void OnTriggerStay(Collider otherObject)
{
if(otherObject.tag == "Enemy") //&& playerEntered)
{
var expPrefab = Instantiate(missileExpObject, this.transform.position, Quaternion.identity);
Destroy (this.gameObject);
Destroy(otherObject.gameObject);
Player.Score +=100;
print ("explode enemy");
}
}
}
Comment
In the Update you need to check if the target object does not exist anymore then execute the FindClosestEnemy again to find a new target.
How :( Because I have no idea how to script that... Like I said I just found this script here.
Please help
Best Answer
Answer by Grim_Darknight · Oct 03, 2013 at 07:03 PM
In the update function you could try adding
if(target == null)
{
closetMissle = FindClosestEnemy();
if(closetMissle)
{
target = closetMissle.transform;
}
}
Thank you for this thread had the same question, thanks very much!