SOLVED: Physics.OverlapSphere breaking? Totally baffled... Help?

Hi there,

I’m having a lot of trouble with my field of view check in my game, I’m at the point where I’m questioning if it’s a Unity bug rather than a code error.

The script itself creates a list of objects within the radius, on layer Entities. It then checks to create another list of entities that don’t belong to the “searching” tribe. If that list != 0 it has seen an enemy and therefore switches to attack.

The problem…

It’s scanning and returning as correct, for about 15 seconds before it totally breaks and stops returning anything…

Anyone have any ideas or critique of my code that might help?

You’re all great.
Goji


IEnumerator FieldOfViewCycle()
    {
        while (true)
        {
            if (debugMode)
            {
                Debug.Log("Fired Fov method");
            }
            FieldOfViewCheck();
            // adding a delay to reduce weight on CPU
            yield return new WaitForSeconds(0.3f);
        }
    }

    void FieldOfViewCheck()
    {
        // Create an array of everything we can see labelled entity
        // including our own tribe
        Collider[] entitiesWithinRange = Physics.OverlapSphere(transform.position, radius, entities);

        // DEBUGGING NOTE: at this stage it still breaks anyway

        if (debugMode)
        {
            Debug.Log(entitiesWithinRange.Length);
        }

        if (entityAI != null)
        {
            if (entitiesWithinRange.Length != 0)
            {
                // Creating a new list each time we scan
                List<Collider> enemiesWithinRange = new List<Collider>();

                // We check every collider we can see that's labelled entity
                foreach (Collider entity in entitiesWithinRange)
                {
                    // if an entity, does not belong to our tribe,
                    // we add it to our enemiesWithinRange list
                    if (entity.gameObject.GetComponent<EntityAI>().followerManager
                        != gameObject.GetComponent<EntityAI>().followerManager)
                    {
                        enemiesWithinRange.Add(entity);
                    }
                }

                // If our enemiesWithinRange list is greater than 0, we have found
                // an enemy and therefore should start hunting
                if (enemiesWithinRange.ToArray().Length != 0)
                {
                    entityAI.SetHuntingTarget
                        (enemiesWithinRange[Random.Range
                        (0, Random.Range(0, enemiesWithinRange.ToArray().Length))].transform);
                    entityAI.SwitchState(entityAI.warState);
                }

                // otherwise, we must not be able to see anyone anymore and therefore
                // go back to following our tribe leader
                else
                {
                    entityAI.SwitchState(entityAI.followingState);
                }
            }
        }
    }

List has a .Count, so please stop doing enemiesWithinRange.ToArray.Length! That doesn’t break your code, but it’s really clunky to read and really slow.

Other than that, who knows? Maybe the entityAI is null. Maybe the layerMask is wrong? Maybe the code isn’t even running?

Since your code doesn’t return anything, I’m not quite sure what you mean by “stops returning anything”. Do you mean that your debugMode check doesn’t print anything at all, even 0? If that’s the case (and you’re not seeing errors in the console), it’s probably that the coroutine on top has stopped running.
If whatever MonoBehaviour’s running the coroutine gets disabled, all coroutines will be stopped. Are you ever disabling the MonoBehaviour? In that case, you probably want to move StartCoroutine(FieldOfViewCycle()) from Awake/Start to OnEnable.

Sounds like you wrote a bug!

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Apologies if I’ve not explained myself clearly in panic. You’re totally right… who knows.

My coroutine fires FieldOfViewCheck() consistently and never stops. But my code stops detecting anything in the Collider[ ] after a little while. I literally don’t do anything in game and it goes from detecting the correct Colliders and working properly, to not being able to see anything.

What have you checked? Where is it going wrong? Is the OverlapSphere hitting finding zero elements?
If it is finding something, are your filters removing all of them?

If it is removing all of them, which part is removing them?

Thanks for your reply :slight_smile:

My debugging seems to point to the Physics.OverlapSphere being the issue. It works for about 20 seconds of untouched gameplay then starts firing strangely (the detected colliders = 0 or 1) until it exclusively returns 0… It’s very strange.

P.s thanks for List.Count tip I appreciated that.

What object is this script attached to? Is it moving with your other objects?

Try drawing it, add this to your script:

void OnDrawGizmos() {
    Gizmos.DrawSphere(transform.position, radius);
}

Is that overlapping things?

it most certainly is overlapping things!

I wish this would have fixed everything, but unfortunately it hasn’t :frowning: I still get the same “yes this works, oh no now it doesn’t” pattern.

Hey there,

You’ve been super helpful so I wanted to let you know this is now fixed!!

Turns out editing your characters position via transform.position doesn’t play well with non kinematic rigidbodies… Simply making my rigidbodies Kinematic has fixed this entirely…

Wooo.

Thanks so much for your help (+ everyone else).

Happy debugging.

Just so you know, when you modify the transform of an object directly, you are bypassing the physics engine and so you’ll have all sorts of problems with collision detection. You’ll always want to use the rigidbody’s methods to move the object.

…and no interpolation.

Thanks this makes sense I think.

I’m going to add to my list to rework my character movement and controller scripts to use rigidbody, which should hopefully improve my general foundations. Sound good?

Running into the same kind of issue, I observed that rigidbody colliders within Physics.OverlapseSphere() radius stop being detected when they completely rest. Do the the Physics engine stops evaluating them?
So I wonder if there is any hidden setting for keeping these rigidbodies “alive”?

I had exactly the same problem. After a while the overlapshere would stop working. tried to isolate it but nothing made any difference. then i came across this post and thought I would give it a go turning on is kinematic on all my rigid bodies and it worked. many thanks for figuring it out. am curious though, is this intended from unity or a unity bug?