Unity3d AddComponent采用变量

时间:2014-07-22 16:08:34

标签: c# unity3d unity-components

详细信息: 在Unity3d上的C#中 搜索了统一文档但该示例不适合我的情况,对于我访问过的其他网站也是如此。 (我没有按照我的意愿列出它们。)

我要做的是将带有构造函数的类变量传递给组件:

CustomComponentClass ccc = new CustomComponentClass(2343, "blop");
gameObject.AddComponent(ccc);

我想知道我正在努力做什么,或者如果我错过了什么......

问题:

gameObject.AddComponent(ccc); -> cannot convert ccc to string.

gameObject.AddComponent<ccc>(); -> Are you missing a using directive or an assembly reference? (i'm not, i'm using a variable and all is in the same namespace)

gameObject.AddComponent<CustomComponentClass>(ccc); -> UnityEngine.GameObject.AddComponent(string) cannot be used with the type arguments

gameObject.AddComponent<CustomComponentClass>(2343, "blop"); -> No overload for method AddComponent takes 2 arguments

无论我尝试什么都行不通。 C#不是真的像javascript,如果我是对的,我们以前能够在js中的addcomponent中传递变量。

上下文 我必须绝对在构造函数中传递它。 我有两个私有的字段,出于安全原因,我无法将其归为静态,常量或公共字段。

选项: 如果答案对我来说太复杂,我可能会进行获取/设置并检查字段是否为空。

1 个答案:

答案 0 :(得分:2)

您绝对不需要将其传递给构造函数。

而是正常创建组件(不带参数),将组件添加到游戏对象,然后在提供必要参数的组件上调用setup方法,并运行构造函数中当前具有的任何代码。