- Home /
How do I make Destroy(gameObject) work in my script?
My code is a little long for me to post the entirety of it, but I was able to recreate the issue I'm having with a much trimmed down script, which is shown below. I'm not including what I did to create the mesh since I feel it is irrelevant to my question, and because the script is trimmed down from my original code, it might seem overly complicated for what I'm trying to do. However, the problem still remains so please bear with me.
using UnityEngine;
using System.Collections;
public class CoreController : MonoBehaviour {
private RaycastHit2D[] leftHits;
private bool moveLeft;
public void createMesh() {
//create mesh
}
void Start () {
moveLeft = false;
tag = "step1";
createMesh();
}
void Update () {
leftHits = Physics2D.RaycastAll(new Vector2(transform.position.x-0.1f, transform.position.y+1.5f/2), -Vector2.right);
if(Input.GetKeyDown("left")) {
moveLeft = true;
tag = "step2";
}
if(!GameObject.Find("step1")) {
if(moveLeft) {
if(leftHits.Length > 0) {
if(tag == "step2" && leftHits[0].collider.gameObject.tag == "step2") {
Destroy(gameObject);
}
}
}
//Part A
if(tag == "step2") {
tag = "step3";
}
}
}
}
This script is attached to a gameObject that is instantiated by another script to many random locations on the x-y plane. Without Part A, if a gameObject detects another gameObject to the left of it with the same tag "step2", the gameObject gets successfully destroyed when I click the left button. Now, I want the remaining gameObjects to have the tag "step3". However, with Part A included, the Destroy(gameObject) line is skipped and every gameObject remains and attains the new tag "step3".
It seems that when I include Part A, the if condition
(tag == "step2" && leftHits[0].collider.gameObject.tag == "step2")
is never true for any of instantiated gameObjects because Part A gets executed first. But why?
Any help would be much appreciated.
Note: I tried FatWednesday's suggestion of putting "return;" right after the Destroy(gameObject) line, but I'm still getting the same problem.
Answer by FatWednesday · Aug 13, 2014 at 08:23 AM
Destroy is not an immediate call, never encountered this issue myself but its possible that something is causing it to be removed from the list of objects to destroy before that list is processed.
In any case, to avoid any of the rest of that method running, you could simply putting a "return;" line after the destroy call, Or if there are other parts of the method you still want to run then I'd suggest setting a flag for something like "hasBeenMarkedForDestroy" and then check that flag before doing any other parts of the method that you want to exclude if the destroy got called.