Tuesday, May 22, 2018

Unity3D Default Script Properties

I get the impression not a lot of people are aware that Unity lets you set the default properties for any script file with serialized fields.  This means when you add that script as a component to a GameObject, those defaults will be applied upon creation.

This is something that doesn't matter that often, but in the right situation can be very useful.  For example, I just completed a task in which I needed to apply a component that plays appropriate selection/activation sounds for a button.  This component requires that I set an audio mixer channel, and fill in lists of which sounds to play.  Since the menu has dozens of button objects, many of which do not have a prefab, these assignments would need to be manually done dozens of times.

This is obviously a chore, and beyond that there's a lot of room to accidentally miss a couple of fields as I went through and did them all.  Using default properties, however, I could avoid those problems. I can simply select the script file, fill in the defaults for those fields, then whenever I added the component the standard sounds and channel were filled in automatically.

For reference, when selecting a script file look for a section at the top of the inspector panel, like so:

Friday, January 12, 2018

A Useful Feature of Unity's Debug.Log

This really isn't hidden, but somehow we've been using Unity for years without ever realizing.  Debug.Log (and related methods) actually have a second argument you can fill in.   Pass it an Object as a second argument, like so:

Debug.Log( "Some sort of problem!", myGameObject );

This will print to the Unity console as normal, but filling in the object means clicking on the log entry will take you to that object in the hierarchy.