I’m trying to select a gameobject with the BaseUnit script by clicking on the son, the collider. A selection rectangle is part of the code and it is working. I believe the relevant portion of the script is this:
private BaseUnit[] _selectedUnits;
{
Ray rayS = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfoModelS;
if(Physics.Raycast(rayS, out hitInfoModelS))
{
_selectedUnits[0] = hitInfoModelS.transform.root.gameObject;
_selectedUnits[0].IsSelected = true;
}
}
There is a error in the first line of the conditional, it says it is impossible to implicitly convert type “UnityEngine.GameObject” into “BaseUnit”. I would appreciate some help, I’m quite new to programing.
Unity has two methods which simplify the search for a certain component which is not directly on the gameobject. First there’s the GetComponentInChildren which will look for the component on the gameobject itself where the method is used on and if none is found it will also search all children for that component. Besides that there’s also the GetComponentInParent method which is the one you’re interested in. If will look for a component on the given gameobject and if nothing is found it will continue the search the hierarchy upwards.
So if you have a collider somewhere on a nested child of your gameobject, you can simply use GetComponentInParent on the collider and it will get you your desired component on any parent.
Note that GetComponentInParent only searches up the hierarchy. So a component that is located in a seperate “branch” would not be found. If your gameobject is not nested / grouped under a common empty gameobject, so it’s directly located in the scene, you can use hit.transform.root.GetComponentInChildren<YourComponent>()