- Home /
Passing a Script Name to a Function
Is this possible? I'd like to be able to input the script name as a parameter in the function like so:
function CacheScript(someVariable : scriptName[], anotherVariable : scriptName)
{
for (var i : int = 0; i < gameObject.Length; i++)
{
someVariable[i] = gameObject[i].GetComponent(anotherVariable);
}
}
Problem is figuring out which type to declare for "someVariable" and "anotherVariable" since I won't know the variable type until I enter the custom script name when I call the function. I've tried researching all the different types I could use to declare the variable type but coming up empty. Any help would be hugely appreciated!
$$anonymous$$adDave and $$anonymous$$evin Harris, thanks for the suggestions. I apologize - I realized that my question wasn't specific enough. "someVariable" array has to be one of many different types of script I'm going to call. So I won't know the type (name of the script) until I run the function.
Since the "someVariable" type could be one of many different scripts, how do I declare the type? Is this possible because the type would have to encompass all of the different scripts I intend to call.
It looks like you're using JavaScript. If so, then by default all of your scripts should inherit from $$anonymous$$onoBehaviour. This means that you should be able to use $$anonymous$$onoBehaviour (or its parent class, Component) as the type for "someVariable".
Thanks $$anonymous$$evin! Wanted to comment earlier. variable : $$anonymous$$onoBehaviour worked like a charm.
Answer by MadDave · Aug 23, 2012 at 03:23 PM
You should be able to use UnityEngine.Object (or just Object) instead of String.
Answer by Kevin Harris · Aug 23, 2012 at 03:55 PM
Have you tried making someVariable an array of Components instead of Strings?
You might also consider GameObject.GetComponentsInChildren if the target game objects are children of the object running the query.
Your answer
Follow this Question
Related Questions
GetComponent with variable script possible? 1 Answer
GetComponent() - Is it possible to pass a string variable as name of the script? 3 Answers
How to get variable from another unknown script ? 1 Answer
How would I make the GetComponent field a variable? 1 Answer
GetComponent via String name? 3 Answers