Mahmoud Anwer
Mahmoud Anwer

Reputation: 162

Destroying particle systems

In my game there is a ball hits a coin then the coin disappeared and a particle system is initialized.

my problem is to destroy the particle system i tried to write

Destroy(effect.gameObject)

but i got an error message tell me that there is no definition for gameObject.

my unity version is 4.6.3

Help will be appreciated.

this is my code

public class CoinDestroyer : MonoBehaviour {
   public Transform coinEffect;
   void OnTriggerEnter (Collider other){
       if (other.tag == "Player"){
           var effect = Instantiate(coinEffect, transform.position, transform.rotation);
           Destroy(effect.gameObject, 3);
           Destroy(gameObject);
       }
   }
}

Upvotes: 3

Views: 990

Answers (2)

Tavoiii
Tavoiii

Reputation: 1

The error you're getting is because the object containing effect is destroyed, I recomiedo you use a script within the system of particles insideof the script should give a life time with the following script:

lifeTime = 1.0f
void Start() {
    Invoke ("SelfDestruct", lifeTime);
}

Upvotes: 0

Everts
Everts

Reputation: 10701

Instantiate returns an object of type Object, the top class in Unity (not the .NET type). Since you use var effect, the compiler is fine making effect an Object. But you need a GameObject since Object has no gameObject member.

var effect = (GameObject)Instantiate(coinEffect, transform.position, transform.rotation);

This is one of the danger of using var instead of strongly type variables. Best would be:

GameObject effect = (GameObject)Instantiate(coinEffect, transform.position, transform.rotation);

In this case, if the cast is missing the compiler will throw an error complaining that Object cannot be GameObject and you need a cast.

I only use var in cases I am 100% sure of the type and it is a long one to write like KeyValuePair<string,List<GameObject>>, else, always the right type.

Upvotes: 2

Related Questions