Noobie
Noobie

Reputation: 55

How can I detect nearby GameObjects without physics/raycast?

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?

Upvotes: 1

Views: 1911

Answers (1)

Programmer
Programmer

Reputation: 125245

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

Upvotes: 1

Related Questions