How attach C# script by argument?
I am not native, so I might write strange English. sorry.
I want to attach the script chosen by argument to GameObject.
Example, when argument = "test1" , I want to attach "test1.cs". when argument = "test2" , I want to attach "test2.cs".
I tried this
public void ScriptAttacher(string StringArgument){
GameObject obj = GameObject.Find("objectName");
obj.AddComponent<StringArgument>();
}
but it didn't work.
How can I implement this function?
thank you.
Answer by KindaiFurutani · Nov 09, 2017 at 01:27 AM
@Dragateobj.AddComponent<Type.GetType(StringArgument)>();
this, Unity says "Unexpected symbol ';'"
@Helliumobj.AddComponent( Type.GetType(stringArgument) as Component );
this, Unity says "Cannot convert type 'System.Type' to 'UnityEngine.Component' via a built-in conversion"
I tried thisobj.AddComponent (Type.GetType (stringArgument));
this worked well, tnak you very much.
What should I do for your answers here?
Answer by Dragate · Nov 07, 2017 at 10:10 AM
AddComponent receiving a string parameter is obsolete. Instead of string parameter, you should add the Type of the class you wish to add. Type.GetType() might help you with your problem.
obj.AddComponent<Type.GetType(StringArgument)>();
https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html https://msdn.microsoft.com/en-us/library/w3f99sx1(v=vs.110).aspx
Answer by Hellium · Nov 07, 2017 at 10:10 AM
I've never done this, but try :
// add `using System;` at the top of your file
public void ScriptAttacher(string stringArgument)
{
try
{
GameObject obj = GameObject.Find("objectName");
obj.AddComponent( Type.GetType(stringArgument) as Component );
}
catch (TypeLoadException e)
{
Debug.LogError("Unable to attach component " + stringArgument);
}
}
Your answer
Follow this Question
Related Questions
How too climb a ladder with the FPS Controller correctly 0 Answers
When writing a txt file, it says sharing violation 1 Answer
How do I fix my UnityEngine Reference? 1 Answer
Location Does Not Change 1 Answer
Turning Off Tag After Collision 0 Answers