Classes and Reference Types!

Objective: Understand what reference types are, how they store information and how they pass said information.

Like my last tutorial where a struct is considered a value type, a class is considered a reference type. This is important to note because in your projects you will be passing around information and it is important to understand how the reference types are passed around.

What is a reference type? Reference types are stored on what is called the heap. What is important is how the data is stored and how the data is passed around. Reference types, unlike value types, don’t store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference types contains a pointer to another memory location that hold the data. We don’t need to worry about pointers in C# since memory management is handled for us.

Reference type example, we already know the class is a reference type as well as strings.

Other reference types are strings, all arrays, class, and delegates.

How is this data passed around? When you pass a value type into a function it would clone the value, but you could not change the original value. A reference type however, you maintain a reference to that object or to that reference value and you can modify it.

Example

How to initialize items from a class

Notice that the class needs to use the new operator.

Now let’s change the name of the sword. In the start method call the change value method

It will auto select the reference method because the data type must match the method it is going to.

Now the sword is “stored” in the class item.

Now the value of sword name is set to Master Sword.

To test if the name changed, we need to set a Debug.Log and attach the script to the main camera.

You can see the name change if you place a Debug.Log before and after the change value method.

This is how a reference is passed around through code and how to manipulate the value of said reference. As I always say, never be afraid to experiment with your code, and I’ll see you in the next tutorial.