Enable/Disable gameobjects based on distance to player

Hello !

When certain gameobjects are too far away from the player, I’d like to set their position back to their original position (the one they have on scene load). But only if that original position is close enough to the player.

So basically :

  • If the object is at its original position initially and the player gets away from it => disable object

  • If the object is at its original position initially and the player gets close to it => enable object

  • If the object is NOT at its original position initially and the player gets away from it but gets closer to original position => teleport to original position and keep object enabled

  • If the object is NOT at its original position initially and the player gets away from it and is far from original position => teleport to original position and disable object

That would require executing code every FixedUpdate from a script that is on a disabled gameobject which doesn’t work.

I can’t think of another clean way of doing this, can you guys help ?

Thanks !

you need the following state checker (pseudo)

if object is at the original position:
  if player moved away: disable else: enable
else:
  if player moved away from the original position: disable else: enable
  teleport to original position

You obviously evaluate this from an active object, not a disabled one.
Also note that FixedUpdate is probably not what you want, Update is called in each rendered frame, FixedUpdate is used for physics updates and will give you laggy results.

So I need to create a Manager or something ?
That somehow gets a list of all concerned objects in the scene on start up ?

If the list is known/static, absolutely.
If not, you need to make a system to efficiently build this list.
Make sure you don’t evaluate everything by distance, if you have many objects this will be your bottleneck, so cull objects early based on some preliminary test.

You can evaluate this in a manager or in a protagonist, both are logical places for these kinds of checks, depending on how you want to organize your codebase.

How about this ?

I create a manager gameobject that has a manager script with an empty list of gameobjects

I attach another script to all prefabs I want to add to that list, get the reference to the manager and add them to the list on their awake method.

That way, for any new such object (whether they are there from the start or instantiated ingame), there will be a copy of them in the list.

Then, when they are destroyed, I can remove them from the list.

Then in the manager, I evaluate, every Update (or every 2-3-whateverIsFitting Updates to use less processing power, as this doesn’t require excessive precision), the distance between each of the 2 players and all objects in the list and then do my logic based upon the values.

I think it could work, but I’m not sure because of what you said : “Make sure you don’t evaluate everything by distance, if you have many objects this will be your bottleneck, so cull objects early based on some preliminary test.”

I have to say that I doubt it would go over the 1000s objects. I’d say maybe 3000-5000 at most for the biggest levels.

What do you think ?

EDIT: Actually, I would use this only for physics based objects, because I can just use Unity’s draw distance for the rest right ? Like item bonuses etc (which don’t have a “reset position” stuff needed) ? So that’s only breakables and enemies, which narrows down the list to only the few 100s, maybe even less.

That’s too much. You can do this for tens of objects, not hundreds, let alone thousands.

First, do as you said, infrequent update (not in every frame) of the list.

But before adding them to the list, cull the objects based on some cheap checks: you can use AABB tests (axis-aligned bounding box) which simply test whether the object’s pivot lies between this and that on all three axes.

Regardless doing this for thousands of objects every time introduces a bottleneck of just cycling through that many objects, querying their transforms and doing comparisons. You need a more sophisticated algorithm to do this properly, based on group culling (logical occlusion), where you essentially dynamically build a list of objects that should participate in the final list of objects that are verified.

Once you have your final list (hopefully not greater than 50-100 items), you can try using my distance-checking utility found here . It works with lists or arrays of Vectors, but you can easily customize it.

Just to chime in real quick since I didn’t see it mentioned anywhere - be sure you’re using distance squared, not distance. This will save you a squareroot and cost you a multiplication instead.

About that part :

I’m not sure I understand what you mean ?

Thanks for the help btw !

EDIT: What about calling OverlapSphere every few frames on the player on the desired radius to update the list ?

That way only the objects in that radius would have their calculation on distance performed.

Exactly, that’s one possible solution. Let Unity do the heavylifting when possible.

And instead of calling Update on the list every few frame I could call it every frame and do the calculation of an incrementing portion of the list (like, index 0 => 20, then 21 => 40) and so on, so that instead of having a big calculation less often, I would have several smaller as often as possible. :slight_smile:

Yes, you can make this as complicated as you need/want it to be. But obviously you want to strike a perfect balance between performance and maintainability. If you can use Unity’s API to help you out, do it, monitor your performance at all times (print out some key performance indicators, do the benchmarks, run profiler …), and make sure you understand algorithmic complexity.

In other words sometimes a bad algorithm can outperform a good one, however as you increase the number of iterations, a bad algorithm might get worse exponentially. This effectively means that everything’s fine with 20 elements (i.e.), but if you hit 150 for some reason, your FPS drops to 10. If you don’t carefully design your bottlenecks you will never fix this properly and thus it will affect your design choices, which is always a bad thing.

Brute-force checking distances for many objects is notoriously hard to nail down properly. Be prepared for many optimization steps if you absolutely need thousands of objects.

There are also specialized spatial structures like kd trees or octrees and such which can help you organize and cluster objects in O(logn) time (and therefore optimally skip over without having to do expensive checks). Perhaps this is too advanced for you, but with thousands of objects you sometimes need to use cutting edge algorithms, or you should use the mathematics package (and Burst compiler), or even DOTS.

Well since I use overlapSphere to only consider the objects that are in the sphere, it will never go over a hundred I guess.
The list will be big, yes, but all objects which will be flagged as ignored will not have any other check done to them than “if (ignored) continue”
So we will only go through like 10% of the entire list every frame, and only less than a hundred will actually have their distance to the player calculated :slight_smile:

I have another issue though :

I want to have the ground/walls etc to be on the same “spatial plane” as the collectible objects (like bonuses etc).
So if you have such an object behind a wall, you can’t see it.

But I want to render the ground/walls from much further away than those objects.

How can I do this ?

I tried using 2 cameras but ended up either hiding one of the layers or having lighting issues

Well isn’t this exactly what your distance lod system is meant to be used for? If they are beyond a certain distance you can disable their renderers. Alternatively, you could use Unity’s build in Lod component to do the same however note that it is based on screen size rather than distance so it will LoD out very small objects sooner than very large ones.

On another note - I totally get orionsyndrome’s sentiment about distance checking objects. It can lead to cache thrashing and is basically leaving free performance on the table but unless you are really pushing the limits here I wouldn’t worry about it for now. I probably do a few thousand distance checks every frame and it doesn’t crack my top ten on the profiler. The biggest hits for me come from Unity components like animators and skinned mesh renderers which means I’d be better off finding ways to work around using those. This is one of those things that if you build a decent interface for it, then it becomes relatively trivial to go back and improve the underlying mechanism later. I’d just say go with the simple approach for now and see what happens. You really might find that you don’t need all the fancy data structures and added complexity at all and then you’ll have saved a bunch of time that can be used to add features and polish. And if it turns out to be an issue you can add that stuff under the hood.

Thing is, if I take into account all collectibles, it will easily go in the thousands. And @orionsyndrome said it was not practical to do this with so many objects, so you have me a little confused :confused:

Thanks for answering though ! :slight_smile:

There’s also Jobs + Burst, it’ll easily x50-x100 the speed of distance calculations.

I thought orionsyndrome’s lib would be enough ?

Computer science time! Test it out.