0

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?

1
  • 1
    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 GameObject Commented Apr 22, 2018 at 0:23

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that the overhead for MonoBehaviour is primarily in the magic methods that MonoBehaviours have: Unity has to examine the class for them and if found, there is overhead on the invokation of them. But that only really matters for Update(). If you don't have an Update() (even an empty one!) then the overhead is virtually zero.
1

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

1 Comment

Not entirely true. You can extend Behaviour or Component instead. Both of MonoBehaviour's superclasses have different levels of functionality available. Eg. Transform is a component while Canvas is a Behaviour

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.