I Can Refer to Any Type of Script in a Script?

Hello, I need to know if in a script I can to refer to any type of sript, and then assign the need. example:

var anyScript:anyTypeScript;
              ^     ^   ^   
              |     |   |
              |     |  OR myScript03 
              |     |   
      myScript01 OR myScript02

thanks

In short, the answer is yes, however, there are some restrictions.

This has to do with inheritance, you can read up on it on wikipedia.

The default script class is the MonoBehaviour, and by default all scripts inherit from it. So if you define your reference variable as a MonoBehaviour you will be able to reference to any other MonoBehaviour script.

The limitation is that you will only be able to access the variables and methods in the MonoBehaviour interface. Meaning that if you have for example ScriptA and ScriptB, if you have a reference to MonoBehaviour class in ScriptC it can point to any of them - but it won’t be able to access any new methods or variables defined in those scripts.

Look at it from a logical point of view - you tell the compiler ScriptC is a MonoBehaviour and it “knows” what that class looks like. Then, you reference it to ScriptA - the compiler will accept that because ScriptA inherits from MonoBehaviour, so it essentially has everything a MonoBehaviour has, however, the compiler doesn’t know of any of the new additions ScriptA add to the MonoBehaviour.

Polymorphism and Inheritances have many cool applications - however - in this case I fail to see the use of that as you will only have access to Update, OnGUI, etc… functions, which are all managed by the game engine anyhow so there’s no point calling them yourself.

If you could elaborate on what you are trying to achieve I’d be more than happy to help out :slight_smile:

Check out this answer about inheritance:

Does Unity support Inheritance and Subclassing? - Questions & Answers - Unity Discussions

I think it might be what you’re after.

You can create a base class that defines the function your after, then have multiple classes extend it.