- Home /
calling a class named by a string
using UnityEngine;
using System.Collections;
using System.Reflection;
public class test : MonoBehaviour {
// Use this for initialization
public void CallShipFabric(string ShipScriptName){
//string is a name of a class/script in the same GameObject
// transform the string into a type
System.Type ShipScriptType = Types.GetType(ShipScriptName, "UnityEngine");
// instanciate a value of this class(didn't work)
ShipScriptType ScriptName;
//link with the good object
ScriptName = (ShipScriptType)this.GetComponent(typeof(ShipScriptType));
//finally able to call a function from the script named by "ShipScriptName"
ScriptName.CallAFunction();
}
void Start () {
}
// Update is called once per frame
void Update () {
}
}
Hello everyone, I need to call a function from a script I will only know the name at runtime(well all are already define but i don't know which one will be used because depend on the player choice). I know function they have because they are all children of an abstract class but have different names.
I have try different thing,but nothing seam to work.
thanks.
Sounds like a case for delegates (google it!). They let you pass methods as arguments.
I think you can do what you're asking for using reflection (google it!) but you really should avoid that approach. A delegate seems like a more appropriate answer to your described problem by far.
Your answer
Follow this Question
Related Questions
Adding parameter to instance of a class during runtime 0 Answers
Multiple Cars not working 1 Answer
Generate Script in Editor Script and GetType() returns null. 3 Answers
Distribute terrain in zones 3 Answers
Dynamic editor dll linking? 0 Answers