#Generic Wrapper Struct not Serializing Correctly

1 messages · Page 1 of 1 (latest)

dense sapphire
#

Have I discoverd a Unity bug? Or am I doing something not allowed?

When I wrap an object in a generic wrapper struct, and then use that struct as a field in a MonoBehavior, the object being wrapped doesn't seem to serialize correctly.

For example, the Debug.Log() line in this example will always print "False", even when no Material is assigned.

{
    public Wrapper<Material> test;
}

[Serializable]
public struct Wrapper<T> : ISerializationCallbackReceiver where T : class
{
    [SerializeReference]
    public T target;

    public void OnBeforeSerialize()
    {
        Debug.Log(target == null);
    }

    public void OnAfterDeserialize()
    {
    }
}```
jovial knot
#

this might be the editor using fake null for serialized fields in MonoBehaviours, and because T isn't restricted to using UnityEngine.Object it's probably not using the custom == operator so the log is technically correct

#

you might try making a small build and testing that

#

or maybe casting directly to material to test

dense sapphire
#

Oh, the editor uses fake nulls? I did not know!

#

Ty for this.

#

Yep, it looks like that was it. Switching to .Equals() for the check is now returning True.

civic girder
#

Equals() is what the == operator uses. You need to use ReferenceEquals() to bypass the unityengine.object override.

wooden nacelle
#

even when ref passing, you'd need unsafe to check the managed pointers like so Unsafe.AreSame<T>(ref TStruct, ref TStruct)