Search code examples
c#unity-game-enginepositionmeshgameobject

how to combine meshes and get click location with respect to main parent in c# using unity


Let's say I have a 3D tower in Unity. The tower is structured such that a Transform parent has children where each child represents a floor of the tower. The children themselves are an empty game object (only component is a Transform) and they are the parent of many (custom) meshes (each grandchild is a separate custom mesh). How do I combine those meshes so that I can click somewhere on a floor of the tower and then get the coordinates of that click with respect to the tower as a whole/local position in the tower?


Solution

  • I would have a dedicated class on the root like

    public class Tower : MonoBehaviour { }
    

    then you can have a MeshCollider (or any Collider but of course you will get the position on the collider not the displayed mesh) on all children and do

    // Get a ray of your click position
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    // Shoot a raycast
    if(Physics.Raycast(ray, out var hit))
    {
        // Try to get the Tower component of the parent
        // bubbles up until it finds according component or returns null
        var tower = hit.gameObject.GetComponentInParent<Tower>();
        // Are we clicking at any child under a Tower component?
        if(tower)
        {
            // get the hit point in world space
            var worldPoint = hit.point;
            // Get the hit point relative to the tower's pivot
            var relativePoint = tower.transform.InverseTransformPoint(worldPoint);
    
            Debug.Log($"You have hit tower at {relativePoint.ToString("G9")}");     
        }
    }
    

    See