Unity Destroy GameObject instantiated clone
Problem
I found your problem and you are a victim of Unity being overprotective. You are trying to destroy the transform component of the clone, but you are not allowed to do that so Unity just ignores you.
Solution
void OnTriggerEnter(Collider info)
{
if(info.name == "Ball")
Destroy(Instantiate(coinEffect.gameObject, transform.position, transform.rotation), 5f);
}
So all you only need this one line. You Instantiate the gameObject component of the effect's transform. Then Destroy it using a timer, I gave it 5f
, or else the effect would be destroyed instantaneously.
Related videos on Youtube
Oscar Reyes
Started as back-end web developer on PHP using Yii on my first project, i am always eager to learn new technologies and so i have started developing in HTML and JavaScript, thanks to my knowledge with JavaScript and my experience on back-end, i am now developing Node.js applications. I am always open to new ideas and better ways to improve code and my self as a developer, i look forward to grow in this field and achieve all my goals Desired technologies to work: Android, Desktop applications, Arduino
Updated on June 04, 2022Comments
-
Oscar Reyes almost 2 years
There's something I'm trying to achieve which is destroy an instantiated object (which is a Particle System). After doing some research, I found the way to instantiate and destroy the instantiated object is this:
public class CoinCollider : MonoBehaviour { public Transform coinEffect; void OnTriggerEnter(Collider info) { if (info.name == "Ball") { GameObject effect = GameObject.Instantiate(coinEffect, transform.position, transform.rotation) as GameObject; Destroy(effect); Destroy(gameObject); } } }
but it seems not to delete it, this object is inherited to one object which is being destroyed. But after making this destroy. it seems to create another gameObject with name "Particle System(clone)" with no parent. How to delete it?
-
apxcode almost 10 yearsWhat do you mean by "this object is inherited to one object which is being destroyed".
-
Oscar Reyes almost 10 years@FunctionR i meant it has an parent object
-
apxcode almost 10 yearsIt should be alright. Check my answer below.
-
-
Oscar Reyes almost 10 yearsyour code was the solution, thank you for that.. how did you know unity does this kind of stuff?
-
apxcode almost 10 yearsI have been using Unity for a while now.
-
Lee over 5 yearsYour solution works. I ran into this trap recently and finally found this. I think this is confusing. If Unity doesn't want us to destroy it immediately it should warn us or throw an exception directly. I checked my code so may times and was upset to found that there was nothing else wrong, I just didn't know it won't be destroyed like that...