I’ve often heard the term “struct” thrown around in the Unity universe by several Youtubers such as Jason Weimann, Code monkey and several others but to be honest I’ve never really used them until recently. You see the “struct” concept is a bit alien to me having come from a web development background programming mostly with PHP, Javascript and back in the day Actionscript. So i finally decided to jump in and learn more about this concept and lo and behold its actually a pretty easy thing to understand and work with…and I’m kicking myself in the ass for having ignored it for so long.
So what is a struct?
To sum it up myself: a “struct” is a lightweight data structure which sits on the stack (not the heap) in memory allocation making it a more efficient data structure to work with.
At first glance a struct might look similar to an object and in some ways they do work the same but they key difference is that an object (which is a reference type) gets stored in the heap while a data structure (which is a value type) gets stored in the stack…making the latter a more efficient data entity. An important thing to keep in mind is that a struct gets initialized immediately while an object is instantiated using the “new” keyword. Objects offer much more flexibility compared to structs so its important to understand the differences between them and make strategic decisions on and when and where to use each data structure in your project depending on your requirements. Below is a more detailed comparison of structs and objects that you should be familiar with:
- Value Type vs. Reference Type:
- Struct: A struct is a value type. When a struct is assigned to a new variable or passed as a parameter, a copy of the data is made. Each instance of a struct is independent, and modifications to one instance do not affect other instances.
- Object: An object is a reference type. When an object is assigned to a new variable or passed as a parameter, the reference to the underlying data is passed, not the actual data. Multiple variables can refer to the same object, and modifications to the object are reflected in all references to it.
- Memory Allocation:
- Struct: Memory for a struct is allocated inline with the variable that holds it. Each instance has its own memory space.
- Object: Memory for an object is allocated on the heap, and variables hold references (pointers) to that memory location.
- Default Initialization:
- Struct: All fields of a struct are automatically initialized to their default values (zero or null) when a new instance is created.
- Object: Fields of an object are initialized to null or default values for reference types, but you need to instantiate an object explicitly using the
new
keyword to allocate memory and initialize it.
- Performance:
- Struct: Due to their value type nature and memory locality, structs can be more performant for certain scenarios, especially when dealing with small, frequently used data structures.
- Object: Objects involve additional overhead due to heap allocation and garbage collection, which might impact performance in certain situations.
- Inheritance:
- Struct: Structs do not support inheritance or polymorphism.
- Object: Objects can participate in inheritance hierarchies and polymorphic behavior.
- Use Cases:
- Struct: Typically used for small, lightweight data structures where copying values is acceptable and performance is critical (e.g., vectors, points).
- Object: Used for more complex data structures, classes, and instances where identity and shared state are important.
There are plenty of use cases for structs and for me personally I’ve mainly been using them for custom list structures but I’m sure ill find more use cases for them in future projects. Below is a code example of how you can use a struct for creating a car items in your game:
[System.Serializable] public struct Car { public string model; public int speed; //Constructor to initialize the struct public Car(string vehicleName, int vehicleSpeed) { model = vehicleName; speed = vehicleSpeed; } //Method to display vehicle information public void DisplayVehicleDetails() { Debug.Log($"Model: {model}, Speed: {speed}"); } } public class StructListSample : MonoBehaviour { //List to store instance of the car struct. This can be modified through the Unity inspector since we serialized the struct. public List<Car> carList = new(); void Start() { //Add some cars to the list manually carList.Add(new Car("Porsche", 350)); carList.Add(new Car("Tesla", 500)); //Output the cars to the console foreach(Car car in carList) { car.DisplayVehicleDetails(); } } }
I haven’t tested the code above as i quickly wrote it out while writing up this post but that should be enough to steer you in the right direction.
Hope you found this article useful and if you did feel free to head on over to my Youtube channel and subscribe for interactive videos.
If you have any questions feel free to connect with me on my Discord server.
Happy Coding : ]