- Home /
Destroy objects within ordered Array by line of sight
Hello,
the code i provided works to the extent, that it rightfully destroys an object if it has the breakable tag and not if it has the unbreakable tag, it also protect objects with the breakable tag behind unbreakable tag objects(as intended).
I want objects in range who have the breakable tag to be destroyed even if they are behind each other(so objects with the breakable tag dont protect the object behind them), i thought ordering them and than just deleting them from closest to farthest would achieve that, but it sadly doesnt.
Any idea why that is the case?
Vector3 spawnPos = transform.position;
float radius = 30f;
Collider[] hitColliders = Physics.OverlapSphere(spawnPos, radius, levelMask);
hitColliders = hitColliders.OrderBy(point => Vector3.Distance(spawnPos, point.transform.position)).ToArray();
int i = 0;
while (i < hitColliders.Length)
{
RaycastHit hitPoint;
Vector3 dir = hitColliders[i].transform.position - spawnPos;
Debug.Log(hitColliders[i].transform.position);
if (Physics.Raycast(transform.position, dir, out hitPoint))
{
Debug.Log(hitPoint.collider.gameObject.name);
if (hitPoint.collider.tag == "breakable")
{
Destroy(hitPoint.transform.gameObject);
}
if (hitPoint.collider.tag == "unbreakable")
{
//dont do anything
}
}
i++;
}
why are you sorting the result of the order does not matter?
I dont understand the question? why am i sorting the collider[]? in order to destroy the objects one after another from closest tp farthest.
this is not a coroutine, right? and every breakable found should be destroyed anyway. so why not iterate and destroy them without sorting?
get all, iterate, check for breakable, destroy...
This is an example, where basically sorting by distance won't work, because while trying to destroy red object, you would find green one
Answer by Esteem · Oct 22, 2018 at 03:56 PM
the Destroy() call queues the object for destruction (and OnDestroy() is called as the last thing in this object's existence which means it's possible to hit an object that you've Destroyed, because it's still there in that same frame.
When you raycast against an object that's destroyable you mark it for destruction and then you raycast against objects behind it but it hits the same object again, marking it again
\\
Edit.: Adding context and sauce:
"Actual object destruction is always delayed until after the current Update loop"
Your answer
Follow this Question
Related Questions
Don't allow raycasts to go through colliders? 3 Answers
OverlapSphere returned collider arrays 1 Answer
OnCollisionEnter-issue 1 Answer
Enemy line of sight using linecast and colliders 1 Answer
Moving objects using raycasting? 1 Answer