- Home /
why do these both codes work similarly when they are put inside update function...
Method1::
{
Collider[] hits = Physics.OverlapSphere(transform.position, radius, enemyLayer);
foreach (Collider c in hits)
{
c.gameObject.GetComponent().TakeDamage(damageAmount);
}
enabled = false;
}
Method2::
{ Collider[] hits = Physics.OverlapSphere(transform.position, radius, enemyLayer);
foreach (Collider c in hits)
{
c.gameObject.GetComponent().TakeDamage(damageAmount);
enabled = false;
}
}
Answer by KalleRosendahl · Jul 04, 2018 at 11:40 PM
because in both methods you are looping through your hits... but the code "enabled = false" has nothing to do with the hits it returns the same both when inside loop and outside, perhaps u want to do c.gameobject.enabled = false;? anyhow the output should be the same since enabled = false doestn depend on the hits
No, my problem is that in $$anonymous$$ethod1, the script will first take damage for all the hits in the array and than the gameobject(in which this script is attached) will be disabled and thats what happening while running this code(No Problem Here). But in $$anonymous$$ethod 2 shouldn't it take damage for the first element in array and than disable the gameobject(in which this script is attached)..But it is also giving same behaviour as that by method1
@$$anonymous$$alleRosendahl said everything here. Those codes are the same (sort of). Let's say you found 10 colliders. in $$anonymous$$ethod1 you loop 10 times calling TakeDamage, and after that you disable the script. In $$anonymous$$ethod2 you loop 10 times caliing TakeDamage and disabling the script in every loop iteration!
$$anonymous$$eep in $$anonymous$$d that disabling the script doesn't magically make the code not run anymore. This flag enabled
is just for Unity callbacks (for example Update / Start) so they won't ba called.
Exactly right. If you want to interrupt the code running in that loop, add a break; or return; to your method.
Answer by xboy691 · Jul 09, 2018 at 04:01 AM
I'm curious to see how the boolean "enabled" is changing the gameobject this is on. If you have a piece of code like gameObject.SetActive(enabled)
in an Update function, its gonna be checking for the value in "enabled" every frame. Because your foreach loop is getting called once per frame, it will run its entire course before SetActive is fed the new value of "enabled". So in one frame, the value of enabled is set to false however many times, but its value isn't actually CHECKED until the next frame. To get these codes to work how you would expect them to, maybe replace the lines enabled = true
and enabled = false
with gameObject.SetActive(true)
and gameObject.SetActive(false)
. Just a guess here, but this is all I can think of.