【发布时间】:2014-07-22 16:08:34
【问题描述】:
详情: 在 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 中传递变量。
背景: 我必须绝对在构造函数中传递它。 我有 2 个私有字段,出于安全原因,我不能将其设为静态、常量或公共。
选项: 如果答案对我来说太复杂,我可能会进行 get/set 并检查字段是否为空。
【问题讨论】:
-
您绝对不需要将其传递给构造函数。而是照常创建组件(不带参数),将组件添加到游戏对象,然后在组件上调用 setup 方法,该方法提供必要的参数并运行您当前在构造函数中拥有的任何代码。
-
考虑过制作 get/sets 但从未想过如何设置 xD 谢谢:P
标签: c# unity3d unity-components