Accessing a function within a script assinged in inspector.

Hi,

how can I do something like the following?

var fnToRun: String;
var script: String;

function Start()
{
    GetComponent(script).StartCoroutine(fnToRun);	
}

Basically, I need to be able to specify the script name and the function in the inspector. However, the snippet above doesn’t work and gives me an error saying: ‘StartCoroutine’ is not a member of ‘UnityEngine.Component’.

How do I achieve this? Any help is much appreciated.

Edit:

I need to be able to call non-static functions.

You need to typecast the returned component to a MonoBehaviour. I’m no javascript coder, but in C# it looks like

((MonoBehaviour)this.GetComponent(script)).StartCoroutine(fnToRun);

(* code not tested *)

i would use send message myself:

var fnToRun: String;
var script: String;

function Start()
{
var scriptObject =  GetComponent(script);
scriptObject.SendMessage(fnToRun);   
}

The problem is that GetComponent returns a Component-reference but only MonoBehaviour components have the StartCoroutine function. You need to cast it to MonoBehaviour to access the function.

var fnToRun: String;
var script: String;

function Start()
{
    var scriptObject : MonoBehaviour = GetComponent(script);
    scriptObject.StartCoroutine(fnToRun);
}

However that's in general not a good approach. You should work with direct references and not with string-based reflection-like calls.

If you really need the function to be dynamically called, at least use a reference to the script:

var fnToRun: String;
var script: MonoBehaviour; // Drag the script-component onto the variable.

function Start()
{
    script.StartCoroutine(fnToRun);
}

Or when the script is located on the same object it's probably easier to use SendMessage:

var fnToRun: String;

function Start()
{
    SendMessage(fnToRun);
}

edit

Since it seems a lot of people are not familiar with the Unity editor here is a tutorial how to add another inspector and how to assign a component to a variable:

Add another Inspector

Assign a script to a variable

You can also drag the GameObject, but Unity will take the first Component that matches the required type. If you have only one script attached you can just drag the GameObject (Same happens with a transform component when dragging an GameObject onto a variable)