How to check if a [Serializable] class object is null or not in Unity C#?

111 Views Asked by At

I have a serializable class object

[Serializable]
public class ScheduledRoutine
{
    public int uid { get; private set; }
    public string TaskName = "";
}

My function want to do check if a ScheduledRoutine object is null or not, I tried with following code but it not work.

void Somefunction()
{
    ScheduledRoutine myroutine;
    if (myroutine != null)
    {
        // Do something when it is not null.
    }
    else
    {
        // Do something when it is null.
    }
}

This function will always go inside to the not null logic. But if I try to get myroutine.uid and there is a null reference error came out...

This function will work when ScheduledRoutine is not a Serializable object... however I need to make it work due to my needs... Any workaround?

2

There are 2 best solutions below

0
Chishiki On BEST ANSWER

If unity finds a serializable object that is null it will instantiate a new object of that type and serialize that.

This only applies to custom classes though, references to other UnityEngine.Object’s get serialized as actual references.

You could make a ScriptableObject derived class or another MonoBehaviour derived class, and reference that. The downside of doing this, is that you need to store that monobehaviour or scriptable object somewhere and cannot serialize it inline nicely.

The other option is to use ISerializationCallbackReceiver and write your own serialization logic.

In this case couldn't you just assume validity, something like this:

[Serializable]
public class ScheduledRoutine
{
    public int uid { get; private set; } = -1;
    public string TaskName = "";
}

And then check for validity like so:

void Somefunction()
{
    // I assume this is just to demonstrate as this wouldn't even get serialized
    ScheduledRoutine myroutine;
    if (myroutine.uid == -1)
    {
        // Do something when it is not valid.
    }
    else
    {
        // Do something when it is valid.
    }
}
1
Paweł Łęgowski On

Your value will be created automatically because its Serialized Object. The simplest way to solve your case would be to ScheduledRoutine derive from ScriptableObject, or you could just add bool to inspector instead of checking for null, other approach could involve using [SerializeReference], but you might need custom inspector for that and it's tricky sometimes.