- Home /
Why is an Instance of Prefab not being Destroyed?
Hey guys,
Not really sure what I'm doing wrong here. I have a prefab with some sounds and colliders on it. Everything works fine when I walk into it.
This prefab needs to be used several times.
When I walk into the first prefab, everything works great and goes as planned.
However, when I walk into the second prefab, everything works great. All the sounds play, etc, but for whatever reason the prefab does not get destroyed.
It just stays there, like nothing happened. I can continue to walk into the colliders and all the sounds will play, etc, but the prefab never gets destroyed?
What am I doing wrong and how do I fix this?
Here's my code:
if (myTrigger.tag == "theTrigger"){
audio.PlayOneShot(mySound);
Destroy(myPrefab);
print("prefab destroyed");
Any ideas?
Thanks in advance!
*Edit to add print("prefab Destroyed");
and prefab destroyed shows up so we know that Destroy(myPrefab);
was called.
Edit Why isn't an instance of a prefab being destroyed?
Where's the ending closing curly bracket? I guess, you just forget it here...
It's not accurate to say "destroy the prefab" - more accurate would be "destroy the gameobject that I instantiated from my prefabs"
Answer by Eric5h5 · Sep 19, 2013 at 03:53 PM
You should destroy the GameObject instance in the scene, not the prefab.
Thanks. I am, myPrefab is the instance. You get an error if you try to destroy the prefab.
O$$anonymous$$, well, I'd recommend using better names, since it's quite confusing calling something a prefab if it's not actually a prefab.
Are you sure you're using an instance? Not sure if you're instantiating or you drag and drop your instances in the editor...
public GameObject prefab;
void YourFunction()
{
GameObject instance = (GameObject)Instantiate(prefab, position, rotation);
}
I'm dragging and dropping the prefabs into the scene.
For example, if it was Super $$anonymous$$ario Brothers it would be 10 coins in the game scene.
I click and drag 10 of my prefabs and and want to collect them. I can get the first prefab and destroy it, but the others prefabs do not get destroyed.
I don't need to instantiate any of them, the prefabs are already layed out ahead of time.
Thanks for the help.
Those are still instances, not prefabs. Dragging a prefab into a scene instantiates it.
Answer by ShinyTaco · Sep 20, 2013 at 02:54 AM
Finally figured it out. I used:
Destroy(myTrigger.gameObject);
Instead of:
Destroy(myPrefab);
Although, I'm still not clear on why you can't use Destroy(myPrefab); (which is an instance of a prefab, not the actual prefab).
Thanks for all who tried to help.
seems like you can not destroy monobehaviours, only gameobjects, glad to see your problem solved :)
@k014: You can destroy anything, not just GameObjects. As you can see in the docs, Destroy is a member of Object, not GameObject.
I guess I should remember this when I might encounter this problem, glad its solved