Make it Serializable! Pt 2

Make it Serializable! Pt 2

Unity is awesome. If you’re reading this you are no doubt aware of my thoughts on it already, but there’s one cool feature I believe is worth specially mentioning as I’ve not seen anyone talk about it before.
I admit this post has been a long time coming but I’ve been spurred on by a recent post by Michael Garforth about serializing private variables so they show in Unity inspector and letting you get back to the strict OOP practices you’ve been taught. I’ve called my post part 2 as his is on a similar topic and should be referred to as part 1. Make sure you read it here!.

Now in your coding travels if you find yourself making custom data classes this is a great way to incorporate them into your Unity IDE experience:
say we have the following class that we will be using as a data structure…

 

using UnityEngine;
public class CustomUV {
    public Rect sourceRect;
    public Rect destinationRect;
}

It’s a simple class with 2 rectangles, probably useful for something to do with UV’s….
Now we might have a component coded up that makes use of a couple of these for something… lets take this pretend behaviour :

 

using UnityEngine;
using System.Collections;
 
public class Pretend : MonoBehaviour {
 
    public CustomUV player1UV;
    public CustomUV player2UV;
 
    // Use this for initialization
    void Start() {
        Debug.Log("Do something cool");
    }
 
    // Update is called once per frame
    void Update() {
        Debug.Log("keep doing cool stuff");
    }
}

This behaviour has 2 variables typed to our custom made customUV type class. Now when you attach this component to a game object you wouldn’t expect to see anything in the inspector… because Unity only serializes base data types right?

Well that’s where the magical [System.Serializable] Attribute comes into play!
Add it to the top of your custom data class so it now looks like this

 

using UnityEngine;
 
[System.Serializable]
public class CustomUV {
    public Rect sourceRect;
    public Rect destinationRect;
}

Now goto Unity and check the game object that had the Pretend component attached…. Holy Serialized Sweetcorn Batman! Bravo, Unity, Bravo.

Note : I used public variables in my Pretend class for the sake of this tutorial. If you read the mentioned article by Michael Garforth you’ll note that’s not necessary with his tricks, you can use them both together to create the ultimate safe, strict and awesome Unity magic.