- Home /
WaitForSeconds...
I have had excruciating tries of finding a solution to this error, but I seem to find nothing. I have a simple cube prefab that spawns, and I want it to be destroyed after a three second delay. I used this:
using UnityEngine;
using System.Collections;
public class Cubes : MonoBehaviour {
public float delay = 0.1f;
public GameObject cube;
public int destroyTimer = 3;
void Start () {
InvokeRepeating("Spawn", delay, delay);
Destruction();
}
void Spawn () {
Instantiate(cube, new Vector3(Random.Range(-6, 6), 10, -2), Quaternion.identity);
}
void Destruction() {
yield return new WaitForSeconds(destroyTimer);
Destroy(gameObject);
}
}
I am getting the same stupid error over and over, no matter what I do. Here it is: "`Assets/Cubes.cs(18,14): error CS1624: The body of Cubes.Destruction()' cannot be an iterator block because
void' is not an iterator interface type`"
Can anyone help me out? Thanks in advance!
Answer by vividhelix · Jul 24, 2013 at 02:27 PM
Use the variant with a delay.
Destroy(gameObject, destroyTimer);
Answer by Hotshot10101 · Jul 24, 2013 at 02:25 PM
yield can only be used inside an Iterator method. An iterator method is best invoked using a corouting.
Try something like this:
IEnumerator DestroyRouting ()
{
yield return new WaitForSeconds (destroyTimer);
Destroy (gameObject);
}
void Destruction ()
{
StartCorouting (DestroyRouting ());
}
The above code will not totally solve your particular problem, however, because you have other problems with the way you are instantiating your objects and such. When you Destroy (gameObject) you are basically destroying whatever object the script is on, not the one that got created during Instatiate. I didn't solve that for you ;-).
Having said all that I was basically answering your question about the specific problem you are having. If it were me I would not use the coroutine method at all. Destroy has a time delay parameter right on it. You just have to use: Destroy (gameObject, x) where x is the number of seconds to delay before destroying. In your case it would be Destroy (gameObject, 3);
That is a possibility, but radlemur's answer is much easier and works. Thanks anyway dude!
If you look at END of my answer I said the same thing as he did. I was just answering your other question about why you were getting the error and how to use it correctly.
I missed that too, otherwise I wouldn't have posted the same thing. When I saw the IEnumerator code I stopped reading.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110748im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Using Yield Wait for seconds with instantiate 1 Answer
Waiting between pingpong loops 2 Answers
Unity Script Editor Not Working 1 Answer
Set Graphics Emulation to No Emulation as Default? 2 Answers