# Destroying 1 of 2 GameObjects with that same script attached in UNITY

So I have 2 GameObjects, and they have 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 :/, I'm confused, any ideas?

Those 2 GameObjects are in the same positions, and I want to delete them by OnTriggerEnter2D

• Ok, but which one do you want to destroy? If you can explain to me how to make that distinction, then you can write that distinction into code. Sep 4 '18 at 20:29
• Did you try implementing singleton pattern. So you won't have 2 of them in first place. Like have a static Instance of itself on Start if null, else delete itself. Then whenever a second one will be created it will commit suicide automatically. ))) Apr 14 at 12:17

Pretty simple. Have the one you don't wanna destroy with a public bool and check it true in the inspector:

//other variables...
public bool doNotDestroy;
//other code...
function OnTriggerEnter(Collider collision)
{
//other statments...
if (collision.gameObject.name = /*name of needed object to hit*/  && doNotDestroy == false)
{
//destroy code...
}
}
//rest of code follows...


Comments indicate places where the rest of your script would be.

• Yea, that would work.. BUT due to my project (procedural dungeon generator) I have to randomly delete ONE of the 2 GameObjects, no matter which one. Im coonfused, I've tried whole night :D Jul 4 '18 at 10:05
• @SewerynPokutycki Please add the fact that it's random to your question Aug 4 '18 at 2:21
• @SewerynPokutycki yes that would be helpful to others: to edit in the fact these objects are generated run-time Aug 4 '18 at 4:33
• I think @The_Mattbat999 got the answer if you got 2 classes, on collision you can get the other.collision.gameObject.GetComponent<Classname> change the boolean that go in collision. Now you can prevent that script been execute on collision. Mar 14 at 20:29

I can put my head through, ok Create An empty gameObject and make your GameObjects Childrens of the former, Add the script and create a private List of gameObjects, Set it in the Start,
Use foreach statement to get the component GameObject,
Instead of Destroy, SetActive the gameObject at the index to False. I think that will do.

• This doesn't appear to answer the question of how to destroy one and only one of the objects via OnTriggerEnter2D. Dec 4 '18 at 5:06

Okay So I found out solution, I've simple checked GameObject's ID and destroy them.

• Thanks for providing the answer! Don't forget to come back in a couple of days to mark it as the accepted one! Jul 4 '18 at 11:46
• @Seweryn can you elaborate on how you did this? Aug 4 '18 at 2:22

Super simple solution use static variables

• Exactly how would you recommend applying static variables to solve this problem? Dec 4 '18 at 12:48