- Home /
GetComponent when I don't know the name
In my code, I am instantiating a clone, then adding a script to it. The script I add is a random behavior script, but each behavior script will have certain variables I then want to change from the script that created the clone.
Right now I have it set like this:
clone = Instantiate (hazard, spawnPosition, spawnRotation) as GameObject;
//scriptAdder is a string with a random script name
clone.AddComponent(scriptAdder);
Now I want something like:
addedScript = clone.GetComponent<scriptAdder> ();
But obviously this doesn't work as I can't send in a string like this, as far as I know?
Anyone have an idea of how to accomplish this as I have it? I'm open to needing to reformat the way things are called if there's no way to do what I'm looking to do, but any guidance would be much appreciated.
Thanks!
All your "random behaviour scripts" should inherit the same script then you do:
ParentScript script = clone.AddComponent(randomScriptName);
You might want to think about the script being added being responsible for collecting the data it wants. Then you could use the AddComponent(someRandomScriptName) and send a message to it telling it what its context is (perhaps why it was added) - or you might just be able to pull the information from the game object itself in the Awake of the added script.
Basically, if you turn your thinking around so you consider that the script needs to demand the information it needs you will have a much more flexible system.
Answer by Noob_Vulcan · Mar 31, 2014 at 05:04 AM
To add component at runtime use this :
void Start () {
this.gameObject.AddComponent ("YourScriptName");
}
Now to get this component Use:
YourScriptName script;
void Start(){
script=this.GetComponent<YourScriptName>(); //use "this" if the script is on current gameobject else use the gameObjectName
}
The problem is that I don't know the script being added, so I can't just call it with the Type like that, as far as I know.
Answer by Looking4Game · Mar 31, 2014 at 10:04 AM
You can use this trick to know which script you added:
YOURSCRIPTCLASS1 temp1 = this.GetComponent("YourScriptName1");
if (temp == null) {
YOURSCRIPTCLASS2 temp1 = this.GetComponent("YourScriptName2");
} else {
//Do what you want.
}