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