[英]how can I pass a C# component from one gameobject to another in Unity3d
我有一个 C# 脚本,名为A
。 A
有很多变量。 我将它放在一个也称为A
的游戏对象上,并在 Inspector 中初始化所有变量。 现在,我有另一个game-object B
,我想将 A 脚本传递给游戏对象B
而不在另一个脚本中初始化变量。 我试过AddComponent()
,但它只是添加了一个脚本,我必须再次初始化所有变量。 但我不想再次初始化所有变量。 我能怎么做?
在您的游戏对象 B 上,您创建一个以 A 作为参数的新脚本:
class B : MonoBehaviour
{
public A AObject;
void Update()
{
// Do something with A
if (AObject.hasPancakes) { ... }
}
}
现在,只需将游戏对象 A 拖到扫描检查器中的此参数上即可。
请参阅 Unity 文档中的访问其他对象。
更新:
就像@joreldraw 说的,你可以从脚本中找到场景中的对象 A 并保存它:
AObject = Find("MyAObjectName").GetComponent<A>();
但是,如果您打算“克隆”组件 A 以便获得副本,那么一种方法是克隆整个游戏对象:
GameObject CopyOfA = Instantiate(AObject);
您现在拥有整个游戏对象的完整副本。
Unity 在运行时不提供CopyComponent
功能。 对于这种情况,您需要与System.Reflection
命名空间交互并获取所需组件的副本并将其添加到当前游戏对象的组件中。 这是一个使用反射的例子。
示例代码:
public class B : MonoBehaviour
{
// Use this for initialization
void Start ()
{
var script = this.gameObject.AddComponent<A> ();
MyExtension.GetCopyOf (script, GameObject.Find ("A").GetComponent<A> ());
}
}
public static class MyExtension
{
public static T GetCopyOf<T> (this Component comp, T other) where T : Component
{
Type type = comp.GetType ();
if (type != other.GetType ())
return null; // type mis-match
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
PropertyInfo[] pinfos = type.GetProperties (flags);
foreach (var pinfo in pinfos) {
if (pinfo.CanWrite) {
try {
pinfo.SetValue (comp, pinfo.GetValue (other, null), null);
} catch {
} // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
}
}
FieldInfo[] finfos = type.GetFields (flags);
foreach (var finfo in finfos) {
finfo.SetValue (comp, finfo.GetValue (other));
}
return comp as T;
}
}
这里MyExtension
是一个扩展类,其中编写了GetCopyOf
函数。
从您的查询中我了解到,也许您想从对象 A 复制组件并将其与值粘贴到另一个对象 B,正如您在检查器中提到的初始化值。 这可以通过编辑器脚本来完成。 要将组件从一个游戏对象复制到另一个带有值的游戏对象,您可以使用 EditorUtility.CopySerialized。 我可以提供一个动画组件的例子,同样可以用于任何组件
Animation srcAnimComponent = srcObjectA.GetComponent<Animation>();//this will get the source component with all the values or data from A
Animation destAnimComponent = destObjectB.AddComponent<Animation>();//this will add the empty component to B
EditorUtility.CopySerialized(srcAnimComp, destAnimComp);//this will copy all the vaules from A comp to B comp
然后如果意图移动,则销毁 A 上的源组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.