Create a class that can be created using NEW but also used as an assignable component

I may need some major Unity voodoo here — or, perhaps, just some good ideas.

I have a datatype kind of class with getter and setter functions. I would like this class to be assignable as a component, so inherit it from MonoBehavior or ScriptableObject.

At the same time, I want to be able to create a class object in code, simply by using NEW. I feel this is necessary because this will be happening quite frequently and having to instantiate a gameobject with all of its cost, just to be able to get and set some data, simply seems like complete overkill.

So, my question is, whether there is a way to have it both ways?

I was thinking about creating an abstract class, but because C# does not allow multiple inheritance that wouldn’t work either because I wouldn’t be able to conflate my abstract class and MonoBehavior into one new class.

I am sure there are ways or tricks to deal with this, so please hit me with ideas and suggestions.

Thanks a bunch!

I think it would make more sense just to make a monobehavior that auto-instantiates a new copy of that data class in Awake/Start, but leave the data class itself as a non-monobehavior. You can still use the same getter and setter names for the monobehavior, and it’ll just redirect to the getter and setter for the data class hidden inside of it. If you need to be able to store both in a list, then a shared interface may work at that point.

Yeah, what you need to do is use a monobehaviour class as a wrapper for your data class. When you are using your data class you’d do something like ‘monoclass.dataclass.datamember’. Just make sure you have your dataclass set as public in monoclass and either datamember set as public in dataclass or use a dataaccess() function instead (‘monoclass.dataclass.dataaccess()’). As Lysander said, you’ll set your monoclass to do something like:

void awake() {
    dataclassinstance = new dataclass();
}

If you need the dataclass to start with specific set data you’ll want to create a setter function in your monoclass that would be called by the instantiating class. If you want the data to be set in the inspector make sure dataclass has [Serializable].

Thanks, guys, let me try that. The critical thing is that, yes, I want the data to be editable in the inspector, so the data fields need to be visible there. I wasn’t aware that [Serialize] achieves that, so I’ll definitely give that a shot.

In order for it to be visible in the inspector you need to have [Serializable] on classes that don’t inherit from monobehaviour and you need to have any members which you want to be visible be public. Both things are necessary.