Guye Incognito
Guye Incognito

Reputation: 2844

Unity3D. How to construct components programmatically

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.

Upvotes: 1

Views: 6133

Answers (1)

Heisenbug
Heisenbug

Reputation: 39194

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.

That's true. A possibility is to istantiate components at runtime and provide a method to initialize them ( if initialization requires arguments, otherwise all initialization can be done inside Start or Awake methods ).

How do I construct the 'component B's programmatically with certain values?

Here's a possible way:

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);
    }
   }
}

Note that in the example above all components will be attached to the same GameObject, this might be not what you want. Eventually try to give more details.

Upvotes: 5

Related Questions