我有一个名为A
的C#脚本。 A
有很多变数。我将它放在一个名为A
的游戏对象上,并在Inspector中初始化所有变量。
现在,我有另一个game-object B
,我想将A脚本传递给游戏对象B
而不在另一个脚本中初始化该变量。
我试过AddComponent()
,但它只是添加一个脚本,我必须再次初始化所有变量。但我不想再次启动所有变量。我该怎么办?
答案 0 :(得分:2)
在游戏对象B上,您创建一个新的脚本,其中A作为参数:
class B : MonoBehaviour
{
public A AObject;
void Update()
{
// Do something with A
if (AObject.hasPancakes) { ... }
}
}
现在,只需将GameObject A拖到scane检查器中的此参数上即可。
请参阅在Unity中访问其他对象docs。
更新
就像@joreldraw所说,你可以从脚本中找到场景中的对象并保存它:
AObject = Find("MyAObjectName").GetComponent<A>();
但是,如果你的意图是&#34;克隆&#34;组件A所以你有一个副本,一种方法是克隆整个游戏对象:
GameObject CopyOfA = Instantiate(AObject);
您现在拥有整个游戏对象的完整副本。
答案 1 :(得分:0)
Unity在运行时不提供CopyComponent
功能。对于这种情况,您需要与System.Reflection
命名空间进行交互并获取所需组件的副本,并将其添加到当前gameObject的组件中。以下是an example使用反射。
示例代码:
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
函数。
答案 2 :(得分:0)
从您的查询中我了解到,您可能想从对象 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 上销毁源组件,如果移动是意图。