James Monger
James Monger

Reputation: 10685

Unable to use Unity script without extending MonoBehaviour

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?

Upvotes: 0

Views: 2973

Answers (2)

Jesus Alonso Abad
Jesus Alonso Abad

Reputation: 261

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.

Upvotes: 4

Chik3r
Chik3r

Reputation: 380

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

Upvotes: 1

Related Questions