- Home /
Accessing GetComponent from a C# List
Hi All,
I have a C# list of colliders (of type List<Collider>
) and I am having a hard time accessing the GetComponent method from the colliders within the list.
Essentially, I assign a collider to the list after a successful raycast.
Ray rayUnit = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hitUnit = new RaycastHit();
int unitLayer = LayerMask.NameToLayer("Unit");
int unitMask = 1 << unitLayer;
if(Physics.Raycast(rayUnit, out hitUnit, Mathf.Infinity, unitMask))
{
hitUnit.collider.GetComponent<Selectable>().selected = true;
selectedUnits.Add(hitUnit.collider);
}
Then later I try to access the collider inside the List:
for(int i=0; i < selectedUnits.Count; i++)
{
selectedUnits[i].GetComponent<Selectable>.selected = false;
}
And this fails with the following error:
error CS0119: Expression denotes a `method group', where a `variable', `value' or `type' was expected
Why can't I access the GetComponent method?
Thanks in advance for any help.
Answer by rutter · May 07, 2012 at 06:31 AM
GetComponent<Selectable> <-- this is what you have, now
GetComponent<Selectable>() <-- note the parens
A function name without parentheses is a reference to the function, which is useful for delegates and so on.
A function name with parentheses calls the function, which looks like what you meant to do here.
It's an easy mistake to make, right up there with missing semicolons and the like, but compilers are quite picky. :)
Thanks. I was staring at this for quite some time yesterday. Good excuse to take a break I guess :)