How can I detect nearby GameObjects without physics/raycast?

天涯浪子 提交于 2019-12-01 10:32:39

问题


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 using colliders or Physics.OverlaptSphere() I don't want to use this method because the only information I need is the Transform of nearby Objects from a given LayerMask (more specifically, the position and rotation) If I would use Physics I would have to put a trigger over every point which I find unnecessary.

Is there other method of finding the nearby points other but similar to the one that uses Physics?


回答1:


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);


来源:https://stackoverflow.com/questions/47365001/how-can-i-detect-nearby-gameobjects-without-physics-raycast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!