Im trying to make a homing missile, that finds its target via Physics.OverlapSphere. But for some reason its not working. And i cant figure out why.

if (!Target)
{
Collider possibleTargets = Physics.OverlapSphere(playerPostion.transform.position, 200);
for (int i = 0; i < possibleTargets.Length; i++)
{
Collider possibleTarget = possibleTargets*;*
GameObject possibleTargetObject = possibleTarget.transform.parent.gameObject;
if (possibleTargetObject.tag == “Enemy”)
{
possibleTargetObject = Target;
return;
}
}
}

Hi @FuturPlanet
you’re not updating your Target variable, you’re updating a local variable (possibleTargetObject) which is wrong.


Other things to check:

  1. Make sure your target game objects have a collider component, and if they are set to isTrigger, then add QueryTriggerInteraction.Collide to your Physics.OverlapSphereNonAlloc 's parameters.

  2. Are your target tags correct?

  3. Are they enabled when you’re looking for a target?

  4. Call your function in FixedUpdate.


This is how I would code it:

    [SerializeField] 
    private LayerMask targetLayers; // or private const int layerMask = 8;
    private const string TargetTag = "Enemy"; // cache your strings
    private const int MaxNumOfTargets = 10; // this is important for not creating garbage, calculate the maximum number of targets
                                            // since Physics.OverlapSphereNonAlloc does not attempt to grow the buffer if it runs out of space.
                                            // The length of the buffer is returned when the buffer is full.
                                            // read more here https://docs.unity3d.com/ScriptReference/Physics.OverlapSphereNonAlloc.html
    
    private bool _haveTarget;
    private Collider[] _possibleTargets;

    private void Awake()
    {
        _possibleTargets = new Collider[MaxNumOfTargets];
    }

    private Transform FindFirstTarget(Transform playerTransform, float radius)
    {
        int size = Physics.OverlapSphereNonAlloc(playerTransform.position, radius, _possibleTargets, targetLayers); // use NonAlloc version, and use layer masks
        for (int i = 0; i < size; ++i)
        {
            Collider possibleTarget = _possibleTargets*;*

if (possibleTarget.CompareTag(TargetTag)) // use CompareTag instead of == operator
{
_haveTarget = true;
return possibleTarget.transform;
}
}

return null;
}
And here is an example of the function usage:
void Example()
{
if (!_haveTarget) // instead of checking for null, store a bool variable and update that.
{
Transform target = FindFirstTarget(transform, 200);
}
}