1

I'm new to unity and am having a bit of trouble getting my head around the architecture.

Lets say I have a C# script component called 'component A'. I'd like component A to have an array of 100 other components of type 'component B'. How do I construct the 'component B's programmatically with certain values?

Note that 'component B' is derived from 'MonoBehaviour' as it needs to be able to call 'StartCoroutine'

I'm aware that in unity you do not use constructors as you normally would in OO.

4

1 回答 1

5

请注意,“组件 B”源自“MonoBehaviour”,因为它需要能够调用“StartCoroutine”

我知道,在统一中,您不会像在 OO 中那样使用构造函数。

确实如此。一种可能性是在运行时实例化组件并提供初始化它们的方法(如果初始化需要参数,否则所有初始化都可以在内部StartAwake方法中完成)。

如何使用某些值以编程方式构造“组件 B”?

这是一种可能的方法:

public class BComponent : MonoBehavior
{
  int id;
  public void Init(int i)
  {
    id = i;
  }
}
}
public class AComponent : MonoBehavior
{
  private BComponent[] bs;

  void Start()
  {
    bs = new BComponent[100];
    for (int i=0; i < 100; ++i )
    {
      bs[i] = gameObject.AddComponent<BComponent>().Init(i);
    }
   }
}

请注意,在上面的示例中,所有组件都将附加到同一个 GameObject,这可能不是您想要的。最终尝试提供更多细节。

于 2013-07-21T19:12:23.390 回答