How can I detect nearby GameObjects without physics/raycast?

前端 未结 1 469
一个人的身影
一个人的身影 2021-01-16 10:45

I am trying to detect the object\'s within a range having the player as origin point. How can I find the Transforms from a given area around the player without

相关标签:
1条回答
  • 2021-01-16 11:11

    If you want yo do this without Physcics or Colliders, access all the objects. Loop through them, check the layer and if they match, use Vector3.Distance to compare the distance of each object. Return the result.

    List<GameObject> findNearObjects(GameObject targetObj, LayerMask layerMask, float distanceToSearch)
    {
        //Get all the Object
        GameObject[] sceneObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
    
        List<GameObject> result = new List<GameObject>();
    
        for (int i = 0; i < sceneObjects.Length; i++)
        {
            //Check if it is this Layer
            if (sceneObjects[i].layer == layerMask.value)
            {
                //Check distance
                if (Vector3.Distance(sceneObjects[i].transform.position, targetObj.transform.position) < distanceToSearch)
                {
                    result.Add(sceneObjects[i]);
                }
            }
        }
        return result;
    }
    

    This can be improved by using Scene.GetRootGameObjects to retrieve all the GameObjects but it does not return Objects that are marked as DontDestroyOnLoad.

    Extended as extension function:

    public static class ExtensionMethod
    {
        public static List<GameObject> findNearObjects(this GameObject targetObj, LayerMask layerMask, float distanceToSearch)
        {
            GameObject[] sceneObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
            List<GameObject> result = new List<GameObject>();
            for (int i = 0; i < sceneObjects.Length; i++)
                if (sceneObjects[i].layer == layerMask.value)
                    if (Vector3.Distance(sceneObjects[i].transform.position, targetObj.transform.position) < distanceToSearch)
                        result.Add(sceneObjects[i]);
            return result;
        }
    }
    

    Usage:

    List<GameObject> sceneObjects = gameObject.findNearObjects(layerMask, 5f);
    
    0 讨论(0)
提交回复
热议问题