Tuesday, May 22, 2018

Unity3D Default Script Properties

I get the impression a lot of people aren't 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:


No comments:

Post a Comment