- Home /
How to destroy a specific Game Object clone in scene?
used array of game object like this and selected prefabs in inspector
public GameObject[] Cards = new GameObject[52];
instantiated game object with this
Instantiate (Cards [i], new Vector3 (xVal, yVal, zVal), transform.rotation);
I tried to destroy game object like this
Destroy (Cards[handOne]);
Destroy (Cards[handTwo]);
and got this error
Destroying assets is not permitted to avoid data loss. If you really want to remove an asset use DestroyImmediate (theObject, true); UnityEngine.Object:Destroy(Object) test:split() (at Assets/test.cs:367) UnityEngine.EventSystems.EventSystem:Update()
Answer by pako · Jun 19, 2015 at 08:37 AM
Your code, as is, tries to destroy the GameObjects held inside the Cards array at index positions handOne and handTwo, not the clone created by Instantiate () in the scene.
If you want to destroy the clone, you need to hold a reference to it. The Instantiate function returns the cloned object, as an Object, so you also have to cast it to GameObject in this case:
GameObject cardClone = Instantiate (Cards [i], new Vector3 (xVal, yVal, zVal), transform.rotation) as GameObject;
Destroy(cardClone);
I'm not quite sure what exactly you want to do, but I'm guessing you might want to have a second array, say CardClones, in which you'd add the clones. e.g. something like:
GameObject[] CardClones = new GameObject[52];
//I guess you have an iterator here to increase 'i' as you create the clones
CardClone[i] = Instantiate (Cards [i], new Vector3 (xVal, yVal, zVal), transform.rotation) as GameObject;
To destroy a CardClone, first hold it in a temp reference, then set it to null in the clones array (if necessary), and then destroy the GameObject that you hold in the temp reference:
GameObject tempCard = CardClone[handOne];
CardClone[handOne] = null;
Destroy(tempCard);
Thank you so much sir! The idea behind the answer works like a charm in my project!
Answer by zaid87 · Jun 19, 2015 at 01:24 AM
This is probably because you're trying to destroy the original prefab (Cards[]) which is an assets and not the Game Objects. If you want to make Game Objects and destroy them and a later (unknown) time, you need to have a variable that point to that Game Object and not at the prefab. For example, when creating:
GameObject newCard = Instantiate (Cards [i], new Vector3 (xVal, yVal, zVal), transform.rotation) as GameObject;
and when destroying it:
Destroy(newCard);
Your answer
![](https://koobas.hobune.stream/wayback/20220613201140im_/https://answers.unity.com/themes/thub/images/avi.jpg)