【问题标题】:Unity3d AddComponent taking variableUnity3d AddComponent 采用变量
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我知道这是旧的。但我也有这个问题,不太了解这个解决方案。 “在组件上调用设置方法以提供必要的参数并运行您当前在构造函数中拥有的任何代码”是什么意思??组件中有设置方法吗?如果是这样,它如何知道要提供哪些参数?抱歉,如果这是一个新手问题,现在已经被困了几个小时了哈哈。
  • 没关系,想通了。我首先设置gameObject.SetActive(false) 添加组件MyComponent myComponent = gameObject.AddComponent&lt;MyComponent&gt;() 然后更改我需要更改myComponent.SetMyVar("example") 然后将游戏对象设置为活动gameObject.SetActive(true)。添加这个以防有人遇到我遇到的同样困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-13
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多