Class Variables: Variables With Multiple Sub-Variables in Unity 3D
In Unity 3D creating variables is quite easy:
public int someValue = 1;
Variable above will be shown like this in the Inspector view:
![](https://sharpcoderblog.com/public/images/fd0/fd08cab823a2805160d51814ce2e80ad.png)
But what if you want to have multiple sub-variables in one single variable? Introducing Class Variables.
Class Variables are variables that use another class as a base type, giving the ability to have multiple sub-variables in one group.
It can be achieved by using a class with [System.Serializable] attribute.
Check the code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SC_ClassVariables : MonoBehaviour
{
[System.Serializable]
public class VariableGroup
{
public Transform t;
public int someValue = 1;
public bool someBool = false;
}
public VariableGroup variableGroup;
}
- The script above defines a class called VariableGroup
- The class VariableGroup contains multiple sub-variables
- Note the [System.Serializable] before the class. This attribute is needed to be able to edit its variables in the inspector view.
- And lastly, the variable variableGroup is defined, which uses the VariableGroup class.
![](https://sharpcoderblog.com/public/images/49a/49a2949cced90074c3364a74223d11fb.png)
The class values are accessed by calling the variable name followed by a dot then a child variable name:
variableGroup.t
variableGroup.someValue
variableGroup.someBool
The class above can also be used in an array:
public VariableGroup[] variableGroup;
![](https://sharpcoderblog.com/public/images/57f/57fb3c24f29efc2f47983e9b0ddb1a2b.png)