Page 1 of 1

Attribute to load into an instance in a field rather than creating new instance

Posted: Fri Sep 16, 2022 10:58 am
by Joel
Status

Requested

Complexity

6/10

Description

This request only regards reference types which aren't stored by reference (i.e. non-UnityEngine.Object types).

Sometimes a class will already have an instance within a field. WIth non-UnityEngine.Object types a new instance will be created when this is loaded. This request is for an option to use the existing instance (if one exists) rather than create a new one.

Anecdote from Falondrian from the Unity thread:
I have some cases of serializable classes that are created inside the constructors of their serializable parent. They get the parent injected into the constructor and do not have parameterless constructors. In this case it would be useful to have an option that says: dont create an instance, just set the properties on the field of the parent - its already instantiated.
5. In the following example the Child does not need to be instantiated by the deserializer because the parent already creates it. It would be fine to set the _someInt field directly on the parent classes _child reference. It would be nice to have an option so this is done automatically.

Code: Select all

[Serializable]public class Child
{
    [SerializeField] int _someint = 0;
    public Child(Parent parent)
    {
        //do stuff with parent
    }
}
 
[Serializable]public class Parent
{
    private Child _child;
    public Parent()
    {
_child = new Child(this);
    }
}