How do I use a spherecast to spawn multiple target images at multiple objects? (script provided)

Hi, how do I make my script spawn multiple target images at multiple objects?

For now the script only targets 1 object at a time, how do I make it so that it targets multiple objects at a time.

   private bool RADSYSB()
    {

        RaycastHit hit;

        Vector3 sy = ship.transform.position;

        if (Physics.SphereCast(sy, range, ship.transform.forward, out hit, 400))
        {
            target = hit.transform;
            distanceF = hit.distance;
            return true;
        }

        Debug.DrawRay(ship.transform.position, sy, Color.green);

        return false;

    }

    private void UpdateCrosshair()
    {
        if (crosshair)
        {
            if (target)
            {
                if (crosshair.gameObject.activeSelf)
                {
                    crosshair.position = ship_camera.WorldToScreenPoint(target.position);
                }
            }
        }
    }

Any help is highly appreciated, thanks in advance

1 Answer

1

Use [SphereCastAll][1] or, better yet, [SphereCastNonAlloc][2], which avoids generating garbage. Here’s some code to get you started:

// We create an array to store the hits that are found.
// Replace 100 with the maximum amount of objects you realistically expect to find.
private RaycastHit[] hitResults = new RayCastHit[100]
private int hitCount = 0;

private void GetHits()
{
    Vector3 sy = ship.transform.position;

    hitCount = Physics.SphereCastNonAlloc(sy, range, ship.transform.forward, hitResults, 400);
}

private void DoSomethingWithTheHitsResults()
{
    for(int i = 0; i < hitCount; i++)
    {
         RaycastHit hit =  hitResults*;*

// Do something with the hit here.
}
}
I think that should point you in the right direction, but let me know if you have questions.
[1]: Unity - Scripting API: Physics.SphereCastAll
[2]: Unity - Scripting API: Physics.SphereCastNonAlloc