Why change void Start() to IEnumerator Start()

I’m watching a video tutorial on a particular learning site. The author says that he wants to change the start function to be a co-routine so he changes it from void to a return type of IEnumerator.

I know what an IEnumerator is, but what I’m not sure about is “why” he might want to change a scripts start function to have this return type. He does not explain this.

I was hoping someone might be able to shed some light on the subject.

Essentually the script is a respawner script where he’s deactivating a target object, yields for a short time randomly finds a respawn location that’s been predefined on the screen, then setting the targets transform to that new respawn locations transform.

All that is happening in the Start function.

Thanks for any help on this…
Rick

@rickblacker

Hi there, I’m definitely not an pro coder, and very seldom use coroutines… but there is an answer to this:

…So it seems unity supports it internally, and maybe it’s just out of convenience, no need to do StartCoroutine from Start?

As the docs (used to) say, Start can be a coroutine. In order for a coroutine to work, it must return IEnumerator.

–Eric

It’s a handy way to make simple little “main loop” type constructs. I use it a fair amount.

But there are some caveats however!

If a GameObject with a script that contains a Start() coroutine becomes inactive then active, the Start() coroutine does NOT resume where it was.

It simply does not resume, since Start() has already been called, in contrast to (for example) if you were doing your logic one slice at a time in Update().

In the latter case, when the GameObject becomes active again, the script’s Update() function will resume getting called.

3 Likes

The reason is to run a coroutine. Coroutines are code that can be executed over multiple frames.

Making Start return an IEnumerator automatically makes it a Coroutine. It’s useful if you need your initialisation to take several frames.

If you are just using Start to trigger coroutines that run through the objects lifetime, I prefer to use StartCoroutine. Using Start for anything other then object initialisation is misleading, and can make your code harder to maintain.

6 Likes

Thanks all… It seems to make since. After reading what you all wrote, and then looking at the doc for coroutine

The best answer to this is ienumerator is basically used to return some thing right so if u want to check that if this thing is on. then return this or wait for second what ever and if this thing is off then do something else why it is better than voidStart() because we cant used wait for second and other thing in it hope this was helpful