Unity:如何将未知脚本动态附加到游戏对象(自定义编辑器)



我目前正在为Unity编辑器(自定义检查器和自定义窗口)制作一个系统,该系统将自动化并使我们正在制作的游戏的美术师更容易,但是我遇到了障碍。

我正在尝试找到一种方法,通过编辑器文本字段输入和 GUI 按钮,将未知脚本动态添加到场景中的游戏对象。 美术师/程序员将在文本字段中输入脚本的名称,它将搜索并添加到游戏对象中,但我不知道如何继续此操作,特别是因为 Unity 5.3 已弃用gameObject.AddComponent()的某些函数

这是我尝试做的:

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);
}
}
}

(当然,这是一个总结版本,我从脚本的不同部分复制了相关台词)。

但它不起作用。 有什么想法吗?

经过广泛的实验,我得到了这个。这也涵盖了所有Unity 组件。只是使它成为一种扩展方法,使生活更轻松。

public static class ExtensionMethod
{
public static Component AddComponentExt(this GameObject obj, string scriptName)
{
Component cmpnt = null;

for (int i = 0; i < 10; i++)
{
//If call is null, make another call
cmpnt = _AddComponentExt(obj, scriptName, i);
//Exit if we are successful
if (cmpnt != null)
{
break;
}
}

//If still null then let user know an exception
if (cmpnt == null)
{
Debug.LogError("Failed to Add Component");
return null;
}
return cmpnt;
}
private static Component _AddComponentExt(GameObject obj, string className, int trials)
{
//Any script created by user(you)
const string userMadeScript = "Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "Rigidbody"
const string builtInScript = "UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "Image"
const string builtInScriptUI = "UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "Networking"
const string builtInScriptNetwork = "UnityEngine.Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "AnalyticsTracker"
const string builtInScriptAnalytics = "UnityEngine.Analytics, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "AnalyticsTracker"
const string builtInScriptHoloLens = "UnityEngine.HoloLens, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
Assembly asm = null;
try
{
//Decide if to get user script or built-in component
switch (trials)
{
case 0:
asm = Assembly.Load(userMadeScript);
break;
case 1:
//Get UnityEngine.Component Typical component format
className = "UnityEngine." + className;
asm = Assembly.Load(builtInScript);
break;
case 2:
//Get UnityEngine.Component UI format
className = "UnityEngine.UI." + className;
asm = Assembly.Load(builtInScriptUI);
break;
case 3:
//Get UnityEngine.Component Video format
className = "UnityEngine.Video." + className;
asm = Assembly.Load(builtInScript);
break;
case 4:
//Get UnityEngine.Component Networking format
className = "UnityEngine.Networking." + className;
asm = Assembly.Load(builtInScriptNetwork);
break;
case 5:
//Get UnityEngine.Component Analytics format
className = "UnityEngine.Analytics." + className;
asm = Assembly.Load(builtInScriptAnalytics);
break;
case 6:
//Get UnityEngine.Component EventSystems format
className = "UnityEngine.EventSystems." + className;
asm = Assembly.Load(builtInScriptUI);
break;
case 7:
//Get UnityEngine.Component Audio format
className = "UnityEngine.Audio." + className;
asm = Assembly.Load(builtInScriptHoloLens);
break;
case 8:
//Get UnityEngine.Component SpatialMapping format
className = "UnityEngine.VR.WSA." + className;
asm = Assembly.Load(builtInScriptHoloLens);
break;
case 9:
//Get UnityEngine.Component AI format
className = "UnityEngine.AI." + className;
asm = Assembly.Load(builtInScript);
break;
}
}
catch (Exception e)
{
//Debug.Log("Failed to Load Assembly" + e.Message);
}
//Return if Assembly is null
if (asm == null)
{
return null;
}
//Get type then return if it is null
Type type = asm.GetType(className);
if (type == null)
return null;
//Finally Add component since nothing is null
Component cmpnt = obj.AddComponent(type);
return cmpnt;
}
}

用法

gameObject.AddComponentExt("YourScriptOrComponentName");

了解我是如何做到的非常重要,这样您就可以在任何未来的 Unity 更新中添加对新组件的支持。

对于用户创建的任何脚本

1.了解Assembly.Load功能中???需要包含的内容。

Assembly asm = Assembly.Load("???");

您可以通过将其放入脚本中来做到这一点:

Debug.Log("Info: " + this.GetType().Assembly);

我得到:Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

我们现在应该用这个取代???

Assembly asm = Assembly.Load("Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");

2.了解asm.GetType功能中???需要包含的内容。

Assembly asm = Assembly.Load("Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
Type type = asm.GetType(???); 

在这种情况下,它只是要添加到游戏对象的脚本的名称。

假设您的脚本名称为NathanScript

Assembly asm = Assembly.Load("Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
Type type = asm.GetType("NathanScript"); 
gameObject.AddComponent(type);

对于不是由用户创建的 Unity 内置脚本/组件脚本

这方面的例子是RigidbodyLinerendererImage组件。只是不是由用户创建的任何组件。

1.在Assembly.Load功能中找出???中需要包含的内容。

Assembly asm = Assembly.Load("???");

您可以通过将其放入脚本中来做到这一点:

ParticleSystem pt = gameObject.AddComponent<ParticleSystem>();
Debug.Log("Info11: " + pt.GetType().Assembly);

我得到:UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

我们现在应该用这个取代???

Assembly asm = Assembly.Load("UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");

2.在asm.GetType功能中找出???中需要的内容。

Assembly asm = Assembly.Load("UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
Type type = asm.GetType(???); 

您可以通过将其放入脚本中来做到这一点:

ParticleSystem pt = gameObject.AddComponent<ParticleSystem>();
Debug.Log("Info: " + pt.GetType());

我得到了:UnityEngine.ParticleSystem

请记住,此处使用ParticleSystem作为示例。因此,将转到asm.GetType函数的最终字符串将按如下方式计算:

string typeString = "UnityEngine." + componentName;

假设您要添加的组件是LineRenderer

Assembly asm = Assembly.Load("UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
string typeString = "UnityEngine." + "LineRenderer";
Type type = asm.GetType(typeString); 
gameObject.AddComponent(type);

扩展方法中将其放在一起

如您所见,添加您创建的脚本和 Unity 附带的脚本/组件需要完全不同的过程。您可以通过检查类型是否null来解决此问题。如果类型为null,则执行其他步骤。如果另一个步骤也null,则脚本根本不会退出。

我建议这样做:

if(GUILayout.Button("Attach script"))
{
// check if type is contained in your assembly:
Type type = typeof(MeAssemblyType).Assembly.GetTypes().FirstOrDefault(t => t.Name == scriptname);
if(type != null)
{
// script exists in the same assembly that MeAssemblyType is
obj.AddComponent(type); // add the component
}
else
{ 
// display some error message
}
}

当然,如果您使用一些包含其他组件的插件(依赖项),这将失败,但要解决此问题,您只需检查程序集的依赖项:

typeof(MeAssemblyType) // your type from Assembly-CSharp 
.Assembly // Assembly-CSharp assembly
.GetReferencedAssemblies() // get referenced assemblies
.FirstOrDefault(m => 
m.Assembly // from this assembly
.GetTypes() // get all types
.FirstOrDefault(t => 
t.Name == scriptname // select first one that matches the name
)
)

言论:

GetReferencedAssemblies方法将只返回由程序集"使用"(加载)的程序集。为了清楚起见,假设您引用了这些程序集:

  1. 系统.Xml,
  2. 牛顿软件Json

而这段代码:

static void Main()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(<some_xml_input>);
}

那么GetReferencedAssemblies的输出看起来有点像这样:

>>> System.Xml, Version=<version>, Culture=neutral, PublicKeyToken=<key>

这意味着它不会加载NewtonsoftJson因为它未在该程序集内部使用。

更好的建议:

我建议您混合@Programmer答案中的方法,但不加载程序集,因为它们已经在 Unity 编辑器启动项目时加载。请改用GetReferencedAssemblies方法,然后从那里调用GetTypes方法来检索该程序集中所有可能的类型。(它会很慢,但会保证你想要的结果)之后,您可以使用FirstOrDefault或自己遍历Type[]以找到所需的那个。

这仍然是可能的。使用这个

UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(GameObject go, "", string componentName);

希望有帮助

反编译 AddComponentWindow of Unity。还添加了链接:
AddComponentAdjust

然后调用窗口,如下所示:

ws.winx.editor.windows.AddComponentWindow.Show(rect);
ws.winx.editor.windows.AddComponentWindow.OnClose += OnCloseComponentSelectedFromPopUpMenu;
ws.winx.editor.windows.AddComponentWindow.ComponentSelected += (menuPath) => ComponentSelectedFromPopUpMenu(positionData.Item1, menuPath);

手柄返回

private void ComponentSelectedFromPopUpMenu(Vector2 position, string menuPath) {


MonoScript monoScript;

char[] kPathSepChars = new char[]
{
'/',
'\'
};

menuPath = menuPath.Replace(" ", "");
string[] pathElements = menuPath.Split(kPathSepChars);

string fileName = pathElements[pathElements.Length - 1].Replace(".cs", "");




if (pathElements[0] == "Assets") {

Debug.LogWarning("Unity need to compile new added file so can be included");


} else if (pathElements.Length == 2) {

//use fileName
//do something


} else if (pathElements[1] == "Scripts") {//Component/Scripts/MyScript.cs


string[] guids = AssetDatabase.FindAssets("t:Script " + fileName.Replace(".cs", ""));

if (guids.Length > 0) {

for (int i = 0; i < guids.Length; i++) {
monoScript = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[i]), typeof(MonoScript)) as MonoScript;
Type typet = monoScript.GetClass();

if (typet == null) continue;




} else {//Component/Physics/Rigidbody
//try to find by type, cos probably Unity type
Type unityType = ReflectionUtility.GetType("UnityEngine." + fileName);

if (unityType != null) {

//do something

return;

}





//Based on attribute  [AddComponentMenu("Logic/MyComponent")] 
//Component/Logics/MyComponent
string[] guids = AssetDatabase.FindAssets("t:Script " + fileName.Replace(".cs", ""));

if (guids.Length > 0) {

for (int i = 0; i < guids.Length; i++) {
monoScript = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[i]), typeof(MonoScript)) as MonoScript;
Type typet = monoScript.GetClass();

if (typet == null) continue;

object[] addComponentMenuAttributes = typet.GetCustomAttributes(typeof(AddComponentMenu), true);



if (addComponentMenuAttributes != null && addComponentMenuAttributes.Length > 0 && "Component/" + ((AddComponentMenu)addComponentMenuAttributes[0]).componentMenu == menuPath)
{

//do somethings

}
}


}


}
}

可以循环访问应用程序域中的程序集。 然后在该程序集的 GetTypes() 中搜索该名称(如 @mrogal.ski 的答案)

static Type FindType(string typeName, string namespaceString = "") 
{
foreach(var asm in AppDomain.CurrentDomain.GetAssemblies()) 
{
var type = asm.GetTypes().FirstOrDefault(t => 
t.Name == typeName && (string.IsNullOrEmpty(namespaceString) || namespaceString == t.Namespace));
if (type != null) { return type; }
}
return null;
}

用法如下:

var someGameObject = new GameObject("FindTypeDemoObject");
var rbType = FindType("Rigidbody");
someGameObject.AddComponent(rbType);
var someMonoBType = FindType("SomeMonoB", "Fake.Example.Namespace");
someGameObject.AddComponent(someMonoBType);

这对我有用obj.AddComponent(System.Type.GetType(ScriptToAdd.name + ",Assembly-CSharp"));

  • ScriptToAdd 是 UnityEngine.Object

相关内容

  • 没有找到相关文章