When working in Unity, I found it useful to do as much as possible within C# scripts.
Having more experience with similar languages, I was more comfortable with that style.
Rather than worry about creating GameObjects and attaching MonoBehaviours to them, I could create simple objects and do as I wished.
Difficulties arose when trying to debug features. Objects created internally through scripts are not visible in Unity's editor. The only way to get information about them was to print to the debug log, which quickly became tedious.
For this reason, I converted several of my C# objects into MonoBehaviours. When the script would create an object of that type, it would instead create a GameObject and attach a MonoBehaviour to it.
Nothing is done with GameObjects, the script retains a reference to the MonoBehaviour. This allows the script to function normally, and for the object to appear in the editor at run-time.
The downside is that MonoBehaviours cannot have constructors. A MonoBehaviour is created by attaching it to a GameObject instead of being created through a constructor. This means that they are not completely initialized upon creation, and will need a separate initialization method.
Using GameObjects also allows the properties of the MonoBehaviour objects to be exposed in the editor. These can be changed at run-time. A practice I've adopted is to rename any property that I want to be visible in the editor with an "editor_" prefix to show that while it is public, other classes should not access it.
No comments:
Post a Comment