Pass SerializeField class to composed class by Editor OnValidate

Greets community,

I wanted to pass a class/struct (i.e. agentLocomotion) of Mob to a class/struct that is composed by Mob (chaseLocomotion) by OnValidate of Editor, so that agentLocomotion of Mob is directly accessible in ChaseLocomotion. Same goes for NavMeshAgent,Transform (even MonoBehaviours) of Mob…

The classes:

public class Mob : MonoBehaviour
{
    [SerializeField] protected AgentLocomotion _agentLocomotion;
    public AgentLocomotion agentLocomotion => _agentLocomotion;

    [SerializeField] protected ChaseLocomotion _chaseLocomotion;
    public ChaseLocomotion chaseLocomotion => _chaseLocomotion;
 
    ...

#if UNITY_EDITOR
    public override void Validate()
    {
        _chaseLocomotion.Validate(this);
    }
#endif

    ...
}

public class ChaseLocomotion
{
    [SerializeField, HideInInspector] Transform transform;
    [SerializeField, HideInInspector] Mob entity;
    [SerializeField, HideInInspector] NavMeshAgent agent;
    [SerializeField, HideInInspector] AgentLocomotion agentLocomotion;

    public ChaseLocomotion(Mob newEntity = null, NavMeshAgent newAgent = null, AgentLocomotion newAgentLocomotion = null, Transform newTransform = null)
    { // ONLY if struct
        entity = newEntity;
        agent = newAgent;
        agentLocomotion = newAgentLocomotion;
        transform = newTransform;
    }

#if UNITY_EDITOR
    public void Validate(Mob newEntity)
    {
        entity = newEntity;
        transform = entity.transform;
        agent = entity.Agent;
        agentLocomotion = entity.agentLocomotion;
    }
#endif
}

public class AgentLocomotion { ... }

I am not sure if this can be passed by constructor or like I did by an additional function.

Unity’s serialisation is by default ‘by values’, so once this asset gets reserialised, agentLocomotion will be a completely new instance. You can get around this by serialising it with [SerializeReference] (both in the monobehaviour and in the class) and they will point to the same instance.

Though for this kind of stuff, I just tend to inject these references in Awake.

I see, but this won’t work for structs because they are value type and not reference?

How would this impact game loading time SerializeReference vs. Awake?

No, structs get passed by value so it will always be a copy.

Not really answerable. You have to measure this.

Nonetheless SerializeReference only affects loading/deserialisation by a tiny amount. Awake also incurs overhead during scene loading.

I can only see either being an issue if you had hundreds, if not thousands of enemies.

If we’re talking only a few dozen, I doubt it will be an issue.

In any case, don’t speculate, measure. Use the profiler.

Thank you, I got it.