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
Answer by oscarAbraham · Dec 23, 2021 at 04:05 AM
Use SphereCastAll or, better yet, SphereCastNonAlloc, 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[i];
// Do something with the hit here.
}
}
I think that should point you in the right direction, but let me know if you have questions.
Your answer
Follow this Question
Related Questions
Seemingly easy Targetting problem! 0 Answers
Switching Target 0 Answers
Constantly Targeting with an InvokeRepeating and Random Targeting 0 Answers
FindGameObject assign in a variable? help! 2 Answers
Camera change targets when new object appears or Camera change targets by pressing a button 1 Answer