Uncategorized

Anatomy of a Unity script

Here’s an example of the default script that Unity will create when you ask for a new C# script:

Most of this makes sense, but I’ve found myself wondering, “why would they include System.Collections, but not System.Collections.Generic?” There aren’t very many cases where I’d rather use an array than a generic List. The other default import, UnityEngine, makes sense because it provides access to the Unity API, but I couldn’t figure out System.Collections.

I discovered the answer while reading through Catlike Coding‘s Unity tutorials (specifically, the tutorial on making fractals):

Move the two child creation lines to a new method named CreateChildren. This method needs to have IEnumerator as a return type, which exists in the System.Collections namespace. That’s why Unity includes it in their default script template and why I included it in the beginning as well.

CreateChildren in the script referenced is a coroutine[ref]See the Unity manual entry on Coroutines for more information[/ref], which provides our answer: Unity coroutines must have a return type of IEnumerator, which is found in the System.Collections namespace. As a core framework feature, it makes sense that the Unity team would choose to include this by default in the new scripts created by the editor.

Leave a Reply