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?
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
ScriptableObjectderived class or anotherMonoBehaviourderived 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
ISerializationCallbackReceiverand write your own serialization logic.In this case couldn't you just assume validity, something like this:
And then check for validity like so: