-1
\$\begingroup\$

I want an object to run code that detects objects around them, in a specific radius.

BUT I cannot use a trigger... or any game objects or components.

What could I do just using code?

\$\endgroup\$
7
  • \$\begingroup\$ Loop through all objects in scene and check distance? \$\endgroup\$
    – Mangata
    Jun 16 at 6:05
  • 3
    \$\begingroup\$ Why you can't use game objects/components? \$\endgroup\$
    – Nikaas
    Jun 16 at 6:40
  • \$\begingroup\$ its a challenge, I would like to see how people attempt it \$\endgroup\$ Jun 16 at 7:12
  • \$\begingroup\$ as for mangata... thats a good idea, but it can only check in a specific radius, so no others are checked \$\endgroup\$ Jun 16 at 7:13
  • \$\begingroup\$ @RyanJohnson What does "it can only check in a specific radius" mean? When you query objects you don't know their distance from you in advance, so you must loop through each of them and check if dist() < radius. That's checking within the given radius to me. \$\endgroup\$
    – liggiorgio
    Jun 16 at 8:24

1 Answer 1

1
\$\begingroup\$

The classes Physics and Physics2D contain several useful static methods to detect Colliders and Collider2Ds within geometric shapes. For example, if you want to get all objects overlapping a sphere with radius 10 around the current gameObject you would do this:

 var colliders = Physics.OverlapSphere(transform.position, 10f)
 foreach(var collider in colliders) {
       Debug.Log($"{collider.gameObject.name} is nearby");
 }

Most of these methods also have "NonAlloc" variants which overwrite an existing array instead of creating a new one. These methods are faster and generate no garbage (especially if you call them a lot), but are a bit harder to use and require that you know an upper limit of how many objects you are going to detect at most.

\$\endgroup\$
3
  • \$\begingroup\$ OP said they "cannot use [...] components". Since Colliders are components, this solution doesn't solve the problem as it's currently stated. \$\endgroup\$
    – liggiorgio
    Jun 16 at 10:40
  • \$\begingroup\$ @liggiorgio Asking how to run code in Unity without using any components is like asking how to build a car without using any tools. This isn't Code Golf; we're supposed to be answering practical questions. \$\endgroup\$
    – Kevin
    Jun 18 at 4:24
  • \$\begingroup\$ @Kevin I totally agree with you, we're supposed to be answering practical questions. But this question has never been about an actual problem in the first place. \$\endgroup\$
    – liggiorgio
    Jun 18 at 8:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .