- Home /
create a destroyer for 2d infinite runner game objects.
hello i have 2d game. I have created an object behind the player which follows the player as he runs infinitely. and put a script that could destroy an object with a tagname. my problem it automatically destroys the object. I want objects to be destroyed when the destroyer object is near or close to the objects i want to destroy.
heres what i got. so far. again this can only delete the objects automatically
public GameObject[] PlatformDestroyed;
void Update()
{
PlatformDestroyed = GameObject.FindGameObjectsWithTag ("PlatformDestroyed");
for(int i = 0 ; i < PlatformDestroyed.Length ; i++)
{
Destroy(PlatformDestroyed[i]);
}
}
Answer by Gocanaroj · Jul 31, 2015 at 09:39 AM
If I'm reading this correctly, you're telling the script to run the for loop on every update frame, which will appear to immediately destroy the object.
One possible solution would be to give the object following your character a collider with "is trigger" checked. Then in your code, put the code that you have now in the "void OnTriggerEnter()" function instead.
Hope this helps. :)
Answer by alteredgene-london · Jul 31, 2015 at 09:52 AM
Hi, using GameObject.FindGameObjectsWithTag on update is a bad idea, because awake is called every frame. Instead putting it under start or awake would be better. For checking the distance between two objects i suggest using Vector3.distance, if your goal is to check their distance Transform would be a better reference for this object rather than GameObject. Assuming you'll attach this script to the destroyer..
public List<Transform> platformDestroyed = new List<Transform> ();
private Transform myTransform = null;
private bool destroy = false;
private float distanceToDestroy = 1;
void Awake () {
myTransform = transform;
}
void Start () {
GameObject[] platformDestroyedObjects = GameObject.FindGameObjectsWithTag ("PlatformDestroyed");
foreach (GameObject gObject in platformDestroyedObjects) {
platformDestroyed.Add (gObject.transform);
}
}
void Update () {
foreach (Transform t in platformDestroyed) {
float distance = Vector3.Distance (myTransform.position, t.position);
if (distance < distanceToDestroy) {
platformDestroyed.Remove (t);
DestroyObject (t);
}
}
}
private void DestroyObject (Transform t) {
Destroy (t.gameObject);
}