Class Variables: Introduction to Variables With Multiple Sub-Variables in Unity 3D

NSDG | Dec 3, 2019 | 0 Comments

In Unity 3D creating variables using C# is quite easy. Check example below:

public int someValue = 1;

Will be shown like this in the Inspector view:

But what if you want to have multiple sub-variables in one single variable?

This approach is useful for when you need to organize the Inspector view or have a multiple variables attributed to a single element.

  • To make the variable like on the image above we need to use a class. Check the code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SC_ClassVariables : MonoBehaviour
    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 edit this variable in inspector view.
  • And lastly the variable variableGroup is defined, which uses VariableGroup class.

The class values are accessed by calling the variable name following by a dot then a variable name:


The class above can also be used in array:

public VariableGroup[] variableGroup;