- Home /
Unity destroy 1 of 2 exactly the same GameObjects with 1 script
So I have 2 GameObjects, and they have the exactly the same script attached to them called 'RoomSpawner'. Via this script I want to destroy just ONE of these TWO GameObjects. How can I do this? By typing Destroy(gameObject); It will destroy 2 GameObjects :/,So I have 2 different GameObjects, and they have the same script "RoomSpawner" attached. I want to destroy one of these 2 GameObjects in this script. If i'd do Destroy(gameObject); then both GameObjects will destroy. Im confused, any ideas?
EDIT: Those 2 GameObjects are in the same positions, and I want to delete them by OnTriggerEnter2D
If they destroy themselves, set condition before calling Destroy. For example set position as condition to destroy:
if (transform.position.t < -6){
Destroy(gameObject);
}
That is not going to work, because my project is a procedural generating levels so i can't set position as a condition :/ And they are in the same position so -
Do you have really a condition or they are randomly selected ? Do you think you can control them with another script, that saves them into array or list, then picks only one needed to destroy? Or you can use static variables that shared along scripts, for example static bool someOneDestroyed, sets to true after OnDestroy, and before calling Destroy check if (someOneDestroyed){ Destroy(gameObject)} . All these are ideas depends on what you have.
Answer by Shameness · Jul 04, 2018 at 01:15 AM
So I have created this component for testing. Attach this script to more than one object, after 2 seconds only one of them going to be destroyed.
public class destroyOne : MonoBehaviour {
static bool otherInstanceDestroyed;
// Use this for initialization
void Start () {
Invoke("killThis", 2f);
}
// Update is called once per frame
void Update () {
}
void killThis(){
if(!otherInstanceDestroyed){
Destroy(gameObject);
otherInstanceDestroyed = true;
}
}
}