我目前正在为 Unity 编辑器(自定义检查器和自定义窗口)制作一个系统,该系统将自动化并使我们正在制作的游戏的美术师的工作更容易,但我遇到了障碍。
我试图找到一种方法,通过编辑器文本字段输入和 GUI 按钮动态添加未知脚本到场景中的游戏对象。艺术家/程序员将在文本字段中键入脚本的名称,它将搜索并添加到游戏对象中,但我不知道如何进行此操作,特别gameObject.AddComponent()是因为 Unity 5.3 中的某些功能已被弃用
这是我尝试做的:
public string scriptname;
GameObject obj = null;
scriptname = EditorGUILayout.TextField("Script name:", scriptname, GUILayout.MaxHeight(25));
if (GUILayout.Button("Attach script"))
{
//search for the script to check if it exists, using DirectoryInfo
DirectoryInfo dir = new DirectoryInfo(Application.dataPath);
FileInfo[] info = dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo f in info) // cycles through all the files
{
if(f.Name == scriptname)
{
//attaches to the gameobject (NOT WORKING)
System.Type MyScriptType = System.Type.GetType(scriptname + ",Assembly-CSharp");
obj.AddComponent(MyScriptType);
} …Run Code Online (Sandbox Code Playgroud)