Get Component from objects in list

Hi,

I am trying to access a script that is attached to all gameobjects that is added to a list but not sure of how to do it.

I was using the sendmessage feature but it becomes to expensive with many selections happening.

void Awake(){
		//Poppulate the SelectableGroundUnits array with all the selectable units that exist
		SelectableGroundUnits = new List<GameObject>(GameObject.FindGameObjectsWithTag("Ground Good"));
		UnitCount = SelectableGroundUnits.Count;
		
	}
	
		
	 
     private void OnGUI()
     {
          marqueeRect = new Rect(marqueeOrigin.x, marqueeOrigin.y, marqueeSize.x, marqueeSize.y);
          GUI.color = new Color(0, 0, 0, .3f);
          GUI.DrawTexture(marqueeRect, marqueeGraphics);
     }
     void Update()
     {
		if (Input.GetMouseButtonDown(0))
		{
			int index = SelectableGroundUnits.Count;
			SelectionController selectControl = (SelectionController)SelectableGroundUnits[index].GetComponent (typeof(SelectionController));
		
		   float _invertedY = Screen.height - Input.mousePosition.y;
		   marqueeOrigin = new Vector2(Input.mousePosition.x, _invertedY);
		
		   //Check if the player just wants to select a single unit opposed to drawing a marquee and selecting a range of units
		   Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		   RaycastHit hit;
		   if (Physics.Raycast(ray, out hit, Range, myLayerMask))
		   {
		        SelectableGroundUnits.Remove(hit.transform.gameObject);
				selectControl.OnSelected();
		  //      hit.transform.gameObject.SendMessage("OnSelected",SendMessageOptions.DontRequireReceiver);
		   }
		}

Just above you can see I have commented out sendmessage, I am trying to call a function (OnSelected) on the SelectionController which is attached to every gamobject that can be selected.

I read it is faster to call it by getcomponent but dont know how to using a list.

Thanks.

New to unity, so i might be wrong but does the following help?
It iterates through the list and calls the SendMessage at every list element.

        foreach (GameObject element in SelectableGroundUnits)
        {
            element.SelectionController.SendMessage("OnSelected",SendMessageOptions.DontRequireReceiver);
        }

oh lol, nvm. I don’t think that’s your question :wink: well atleast i tried haha.

Hey thanks for trying Rick!

You can try by getting the component on the hit collider:

if(hit.transform.gameObject.CompareTag("Ground Good"))  {
SelectionController  selectControl = hit.transform.gameObject.GetComponent<SelectionController>().OnSelected();
 }

This way is a direct reference to the method, but it defy the need of a List to check, and if it doesn’t find anything will return errors, so you may need additional failsafe.

If you need the List route for other purpose you may want to create a List of SelectionController instead of game objects, this way you have direct access to the component and can still reference the gameObject if you need it.