The question is answered, right answer was accepted
Add a script to a GameObject via script at runtime?
I have a number of prefabs that are not very different aside from the scripts attached to them. I was wondering if there was a way to use AddComponent or something similar to add scripts to a newly-Instatiated GameObject using a variable to identify the script. I couldn't find this in the documentation and experimented with strings named after the script or feeding a script into the function unsuccessfully.
So, in brief, what I'm looking for is something like:
void CreateObjectWithScript(string scriptName){
GameObject go = (GameObject)Instantiate(new GameObject, new Vector3(), Quaternion.identity);
go.AddComponent<scriptName>();
}
This way, rather than creating a script and a prefab for each such object, I can just create one generic prefab and attach scripts to them at runtime, deriving any changes needed out of the script.
However, the above code gives me the error: "'scriptName' is a variable but is used like a type"
I tried also using "go.AddComponent(scriptName.GetType());" , but in implementation, naming a script would give the error: "'ScriptToBeAdded' is a type, which is not valid in the given context."
Following that, I have also attempted:
private void Start() {
CreateObjectWithScript(ScriptToBeAdded);
}
void CreateObjectWithScript (Type type){
GameObject go = (GameObject)Instantiate(new GameObject(), new Vector3(), Quaternion.identity);
go.AddComponent(type);
}
This gave the same "'ScriptToBeAdded' is a type, which is not valid in the given context." error as before.
what is the error you are getting? your script example looks correct
idk if that will compile as it's a string in place of a type identifier
"'scriptName' is a variable but is used like a type" is the error from this code snippet.
I have updated the question with some other things I attempted following reading this error. Hopefully they help.
Answer by Antoids · Apr 07, 2018 at 08:52 AM
Solved it myself after messing with it for a bit. The following code will achieve the desired effect:
public GameObject prefab;
private void Start() {
CreateObjectWithScript(prefab, typeof(ScriptToBeAdded));
}
void CreateObjectWithScript (GameObject prefabName, Type type){
GameObject go = (GameObject)Instantiate(prefabName, new Vector3(), Quaternion.identity);
go.AddComponent(type);
}
There's a more natural way to pass Type arguments to functions, btw:
void CreateObjectWithScript<T> (GameObject prefabName){
GameObject go = (GameObject)Instantiate(prefabName, new Vector3(), Quaternion.identity);
go.AddComponent<T>();
}