Unity C#: Classes & Structs

Hal Brooks
3 min readFeb 22, 2022

Objective: Create a customer database for customer information.

A class should be used when repetitive data are entered varying by instance, such as customer information. A Customer_Database is an empty game object in Unity with a CumstomerDatabase script attached. The script inherits from MonoBehavior because it is attached to a game object, see below. It then defines a private _customer variable array using SerializeField, but what is Customer?

Customer is a class which that does not inherit anything. The class Customer contains the variables that define class, but does not assign them. Rather, it contains a constructor or method, Customer, which can be called to assign the class, provided it receives the required information. The System.Serializable before the class declaration allows the class to appear in the inspector.

Now looking back at void Start() in the CustomerDatabase script, the array can be initialized, and the first three elements of the array assigned using code as shown below.

This assignment of each customer relies on the CreateCustomer() method, which uses the Customer() method within the Customer class to assign the individual values to a local variable customer. The customer is then returned and used to populate the _customer array.

Alternatively, the _customer array can be completed using the inspector, since the class is System.Serializable, exemplified below.

Define customers using serializable fields in inspector.

Should the example above be a struct or a class? How is the Customer script going to be used? If another script will inherit from the Customer, then it needs to be a class. If the Customer information needs to be changed by other scripts then it needs to be a class. If only copies of the Customer information are required then the class declaration can be replaced with struct.

Struct vs class declaration depends on use.

A struct is a value type and is stored in the stack, whereas a class is a reference type and stored in the heap. A class contains a reference to a specific memory value thus the value for different references are linked, whereas a struct has a local value, not linked to other objects.

--

--