Can I add global properties to all classes? Like Behaviour.enabled but Behaviour.myOwnThing?

This crossed my mind when trying to conceive of how to do a tooltip system for my UI,
where I might want my cursor script to access something like a “Tooltip text” string for different things with different classes, where I can store that text on a specific instance of that class.

I know I can just write a new small script to store that text and have the cursor look for that component specifically. Which is what I’ll do for now. but this seemed like the kind of question that I could learn something from.

The short answer is that you can’t. An important concept in Object Oriented Programming is Encapsulation (and Separation of Concerns)- the idea that each object should only ever deal with its own data, and never any other data, and that it exposes only what you need to use the object, but nothing about its internal workings. Basically its the principle of ‘I don’t care how you do it as long as it gets done’.

Behaviour is Unity’s class and does what it does. Other classes, like MonoBehaviour, and all of the scripts that derive from it, can extend upon what it does, but can’t change what other subclasses of Behaviour do. Now, it is possible to create an class with a virtual method that returns the tooltip string, and then make all of your UI elements inherit from that class and override that method as needed.

There is something in C# called an extension method, but those can’t be inherited and what they do is more along the lines of adding a convenient way to use a type rather than change what that type actually does, and aren’t suitable for what you’re trying to do.

Adding something ‘to all classes’ or ‘to all siblings’ is something you can’t do because you really should never do it anyway. It might seem tempting now, but how would you keep some other class from trying to do the same thing, overwriting or conflicting with each other or completely bloating the parent class with data its child classes won’t need or might use on their own? It’s one of those things where the language is really saving you from yourself in the long run- a bit like type safety or bounds checking.

So the short answer is you can’t, because you shouldn’t. However, you can make a class that does have that data and inherit from that, or you can continue using your current system.