C# properties

When assigning values to class variables, such as MyClass.x = 10;, there are a couple of important things to take care of. First, you'll typically want to validate the value being assigned, ensuring that the variable is always valid. Typical cases include clamping an integer between a minimum and maximum range or allowing only a limited set of strings for a string variable. Second, you might need to detect when a variable changes, initiating other dependent functions and behaviors. C# properties let you achieve both these features. Refer to the following code sample 1-15, which limits an integer between 1 and 10 and prints a message to the console whenever it changes:

01 using UnityEngine; 02 using System.Collections; 03 //------------------------------------------------------ ...

Get Mastering Unity Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.