yield WaitForSeconds error

void castFire() {
Instantiate(fireSpell, EnemyLocation.position, EnemyLocation.rotation);
yield WaitForSeconds(2);
Destroy(fireSpell);
}

Getting an error on this script…

I want to instantiate a prefab particle effect, 3.5 doesn’t have destroy in the particle effect anymore. So I want to wait 2 and then destroy object.

Error seems to be on the yield WaitForSeconds(2); line according to mono develop…

Unity Error: error CS1525: Unexpected symbol (', expecting )‘, ,', ;’, [', or =’

You can only use yield that way if you’re writing Unityscript (C# needs to use “yield return new WaitForSeconds(2);”), and a coroutine can’t return void, it has to return IEnumerator. Also that won’t work since you need to destroy the instance that Instantiate returns, not the prefab itself. Anyway you don’t need to use a coroutine at all, just do

Destroy (Instantiate(fireSpell, EnemyLocation.position, EnemyLocation.rotation), 2);

In C# you must write:

yield return new WaitForSeconds(2);

But there are several other issues:

1- the function must be a coroutine, which means it must return IEnumerator and be called via StartCoroutine.

2- you’re actually destroying the prefab, not the instantiated particle emitter - you should assign the Instantiate result to a variable to have a reference and be able to destroy the objected instantiated, not the prefab.

But you don’t even need to use a coroutine in this case:

public GameObject fireSpell; // the prefab

void castFire() {
    GameObject fire = Instantiate(fireSpell, EnemyLocation.position, EnemyLocation.rotation) as GameObject;
    Destroy(fire, 2); // destroy fire automatically in 2 seconds
}

You are mixing up unityscript and C#. Here is the correct implementation :

IEnumerator castFire() // Not void
{
    GameObject inst = Instantiate(fireSpell, EnemyLocation.position, EnemyLocation.rotation) as GameObject;
    yield return new WaitForSeconds(2); // added "return new"
    Destroy(inst); //I don't think you want to destroy firespell, but it's instance
}

Note that this function will be executed only if it’s called with StartCoroutine( castFire() ), or StartCoroutine( “castFire” ).

Also, if you just want to wait before destroying it, Destroy has an overload taking a float as second parameter doing just that.