在运行时将一个游戏对象组件添加到另一个具有值的游戏对象中 [英] add one gameobject component into another gameobject with values at runtime

查看:30
本文介绍了在运行时将一个游戏对象组件添加到另一个具有值的游戏对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时我想将一个游戏对象组件复制到另一个游戏对象.

就我而言,我有一台相机,其中添加了多个带有值设置的脚本.

In my case I have one camera where multiple scripts are added with values settings.

我想在运行时添加到另一个相机的相同组件.到目前为止,我已经尝试过,获取对象的所有组件,然后尝试添加,但它不起作用.

The same components I want to add into my another camera at runtime. I've tried this so far, getting all components of an object then trying to add but it is not working.

Component[] components = GameObject.Find("CamFly").GetComponents(typeof(Component));
for(var i = 0; i < components.Length; i++)
{
   objCamera.AddComponent<components[i]>();
   ///error in above line said adds a component class named/calss name to the gameobject                    
}

推荐答案

我建议设计您的应用程序,以便您可以调用 实例化 并获得一个克隆.比您想要的更容易、更快.
但如果你坚持,你可以使用 这个答案中的代码 在 Unity 论坛上.

您得到错误的原因是,您尝试将完全相同的组件(而不是它的副本)添加到另一个对象,即您想强制该组件同时拥有两个父母,这是不可能的(也不可能从原始父母撕下"并移交给新父母;为了模拟"这种效果,您还应该使用代码 -或类似 - 我已链接).

I'd recommend designing your app so you can call Instantiate and get a clone instead. Easier and faster than what you want.
But if you insist, you can use the code from this answer on Unity forums.

The reason of the error you get is, you try to add the very same Component (and not a copy of it) to another object, i.e. you want to force the Component to have two parents at the same time, and that's not possible (it's also not possible to "rip it off" from the original parent and hand over to a new one; for 'simulating' that effect, you should also use the code -or similar- I linked).

这篇关于在运行时将一个游戏对象组件添加到另一个具有值的游戏对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆