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

Vote for new features, or make your own requests here.
Post Reply

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

Yes, I would like this feature
0
No votes
No, I would not like this feature
0
No votes
 
Total votes: 0

User avatar
Joel
Moodkie Staff
Posts: 5036
Joined: Wed Nov 07, 2012 10:32 pm

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

Post 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);
    }
}
Joel @ Moodkie Interactive
Purchase Easy Save | Contact | Guides | Docs | Getting started
Post Reply