P
P
Pragma Games2022-02-04 09:39:03
Unity
Pragma Games, 2022-02-04 09:39:03

Isn't it dangerous to serialize classes in this way regarding unity?

Hello. A little long question for you in the feed)). In my project, I would like to drop the monobehaviour classes in the main logic. Do something like this:

public class Tower : MonoBehaviour
{
    [SerializeField] protected HealthComponent healthComponent;

    private ArmsComponent _armsComponent;
}

[Serializable]
public class ArmsComponent
{
    public int typeArm;

    // Логика класса
}

[Serializable]
public class HealthComponent
{
    public int health;

     // Логика класса
}


That is, to divide the logic of a single entity into various components and then, using composition, assemble other various entities. And for convenience, of course, I would like to have access to such classes (Not inherited from monobehs) from the inspector. I marked them with the [Serializable] attribute, and everything seems to be fine. But here the nuances, as far as I know, [Serializable] cause the recursive creation of classes that fit the serialization type, even if they are private, but inside they are marked with [Serializable] attributes. For example:
[Serializable]
public class HealthComponent
{
// Visible from the inspector
public int health;
// Not visible from the inspector, but it will be serialized since the class itself is also marked with the [Serializable] attribute
private ArmsComponent armsComponent;
}

Of course I know about the existence of [NonSerialized]. And all such places can be marked with this attribute.
And then the questions are: How important is this? Is this approach normal in general (marking logical classes with [Serializable] only so that the data is visible in the inspector. How does this approach differ from what MonoBehaviour uses in their work (Or is it the same thing and monobehs inside are also simply marked with this attribute )?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2022-02-04
@freeExec

// Not visible from the inspector, but it will be serialized

What evidence is there for this assertion?
The rest of your thinking is correct. It's terrible to inherit a data class from MonoBehaviour and not use it as a component in the scene.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question