Property Backed MonoBehaviour using inspector variables

Code

using System;
using UnityEngine;
 
namespace com.mypackage
{
    public class MyControllerWithProperties : MonoBehaviour
    {
        public String _aString;
 
        protected String aString;
 
        virtual public void Awake()
        {
            //copy down inspector value
            if (String.IsNullOrEmpty(_aString))
            {
                aString  = "default";
            }
            else
            {
                aString = _aString;
            }
        }
 
           //an auto property would work too, but only in Unity 3
        public String AString
        {
            get { return aString;  }
            set { aString= value; }
        }
    }
}

Commentary

This is an example of how to shadow Unity inspector variables with real properties. Notice the trick with the public instance variable, the underscore is not visible because the field pretty print in the Inspector ignores non alphabetic characters so _aString and aString look the same to the user. I'm not really worried about Unity doing anything with the variable although that is certainly in the realm of the possible. I am more worried about users using the public field at runtime for properties that would allow them to circumvent any useful stuff in a real property, like property change notification or content checking.

Snippet Usage

Unless otherwise stated, the content of this page is licensed under GNU Free Documentation License.