Home > OS >  Why can we put the result of a GetComponent<Camera> in a Behaviour array but can't do Get
Why can we put the result of a GetComponent<Camera> in a Behaviour array but can't do Get

Time:11-08

I wanted to know why this work :

Behaviour _BehaviourArray = new Behaviour[1];
BehaviourArray[0] = GetComponent<Camera>();

But not this :

Behaviour _BehaviourArray = new Behaviour[1];
TryGetComponent<Camera>(out BehaviourArray[0]);

Which is supposed (in my mind) to give the same result if both Camera components exists.

If someone can answer me it would be highly appreciated.

Thanks.

CodePudding user response:

The indexer operator in C# is a property (or at least acts like one) and thus can't be passed into a method as an out parameter, just like any other property.

A property (or an indexer) is syntactic sugar for a getter and a setter method internally and passing it into another method as a parameter is like writing the following:

TryGetComponent(out BehaviourArray.SetValue(0, ...));

What you can do is write

Behaviour _BehaviourArray = new Behaviour[1];
TryGetComponent<Camera>(out Camera camera);
_BehaviourArray[0] = camera;

You may even wrap this in a method:

void GetComponentToArrayIndex<TComponent, TSpecificComponent>(TComponent[] array, int index) where TComponent : Component where TSpecificComponent : TComponent
{
    TryGetComponent<TSpecificComponent>(out TSpecificComponent component);
    array[index] = component;
}

and use it like this:

Behaviour _BehaviourArray = new Behaviour[1];
GetComponentToArrayIndex<Camera>(_BehaviourArray, 0);

Those are just suggestions and untested code, but that's what I would try in your case.

More info:
Indexers
out parameter modifier

  • Related