Variable Type for an Instance of any Script

Hello,

I have a group of scripts which all contain a public ‘Run’ function.

I need to have an array of different instances of these scripts which I can call the ‘Run’ functions from, but what variable Type do I use?

E.g. I tried using Monobehavour:

var arrayOfScripts : Monobehaviour[];

public function callScript (scriptNumber : int) {
	arrayOfScripts(scriptNumber).Run();
}

But, I get the error: ‘Run’ is not a member of ‘Monobehaviour’.

I have also tried Component and Object.

The array needs to be of the instances of the scripts which exist in the scene attached to objects.

I cannot use the script name as it needs to be an array of different types of scripts which have different names.

I could use a js Array, but I would like to be able to drag and drop into the Inspector without having to create a custom inspector.

I can’t use an array of GameObjects and use Broadcast Message because two scripts may be attached to the same gameObject and I only want one of them to have ‘Run’ called.

Any ideas?

You should implement Interface.

Here is how to do it in C#, I hope you’ll be able to convert it to java yourself:

  1. Create a custom script like this:

    public interface ICanRun
    {
    void Run();
    }

  2. Add interface to your scripts like this:

    public class RunningPlayer : MonoBehaviour, ICanRun

3)Now declare your array like this wherever you like:

ICanRun[] runnersArray;

Obviously with all array-related restrictions, so if you want to dynamically populate it would be better to you something like List for example:

System.Collections.Generic.List<ICanRun> runningList = new System.Collections.Generic.List<ICanRun>();

4)And then in your function just do something like this:

public void callScript(int iNumber)
{
    runnersArray[iNumber].Run();
    //same for list
}

You could derive them all from a base (and/or abstract) class that has the Run function and then store an array of the base type. (rough C# code below)

public abstract class BaseRunner : MonoBehaviour
{
	public abstract void Run();
}

or

public class BaseRunner : MonoBehaviour
    {
    	public virtual void Run(){}
    }

Then derive all of your other scripts from base class:

public class ChildClass : BaseRunner
{
    override void Run()
    {
    }

}