0
votes

I have created a Unity C# script which I want to use to store data for the objects it's attached to.

The class only has two fields, and does not have any behaviour. Because it doesn't have any behaviour, it feels unnecessary to extend MonoBehaviour.

Ideally I would like to extend nothing at all, but I have also tried to extend Behaviour (which MonoBehaviour extends) and in both cases I get the following error in the sidebar against the script:

The associated script can not be loaded. Please fix any compile errors and assign a valid script.

Is it possible for me to attach a script to an object without that script extending MonoBehaviour?

2
You cannot attach non MonoBehaviour class to a GameObject but you can use non MonoBehaviour classes to hold data you want to serialize and save. You just have to use that class from your MonoBehaviour script but you can't attach it to a GameObjectProgrammer

2 Answers

4
votes

Unity makes certain assumptions when using scripts attached to game objects, and one of the ways to make them safe is to impose the scripts to be subclasses of MonoBehaviour.

In my opinion it's fine to have an "entity class" attached to your game object. While normally both the data and its behaviour should come together, sometimes you might set up your game/application to have a middle-man object that accesses other objects' properties. For instance, an AI agent that inspects the health points of nearby enemies to choose the weakest one. So if you feel justified to attach a script just to add data to game objects, go for it, even if it means extending MonoBehaviour.

1
votes

No, you can't add scripts to GameObjects if they don't extend MonoBehaviour