Deal damage to a random Child
Hello there!
Right now, my Script should do the following: Take in the damage from another script. Iterate over all children with health Scripts and distribute the damage in 5 portions randomly among them. If one of them is tagged as a Leader, I'd like it to have a reduced hit chance.
What is happening in my game: Unity randomly freezes as soon as the damage gets parsed in (like, really random. It works 90% of the time, the rest, unity freezes over without further ado. Also, the leader is getting hit more often then any other corps, evenso unity detects the numbers correctly.
Please, wise fellow coders, look at my code or give me examples how it could solve this differently and I'd be forever grateful!
float chanceToReceiveDamage = 0.1f;
public void takeDamage(float damage) {
damageSplittedAmong = 4;
while (damageSplittedAmong >= 0) {
foreach (Transform Corps in transform) {
if (Corps.GetComponent<CorpsDamageHandler>()) {
if (Corps.tag == "Leader") {
chanceToReceiveDamage = 0.5f;}
if (Random.Range(0, 1f) <= chanceToReceiveDamage) {
Corps.GetComponent<CorpsDamageHandler>().TakeDamage(damage));
damageSplittedAmong -= 1;
}
if (Corps.tag == "Leader") {
chanceToReceiveDamage *= 2f;
}
}
}
We Rock!
Answer by Fair-Strides · Aug 14, 2016 at 02:56 AM
@maewionn: I'm thinking that you aren't including the entire takeDamage function, but from what I'm seeing here, I'll read your script back to you:
Everything has a 10% chance to take damage.
Five can take damage, so keep going until all five have taken damage (This assumes that there will always be five targets, so the object automatically must always have five suitable children).
Loop through every transform and check if it has the CorpsDamageHandler script/component.
Assuming all the above is true, if the current child is tagged as the leader, it has a 50% chance to take damage. If Random.Range is successful, give Leader the full damage amount and reduce the number of targets by one.
In the same loop checking for the CorpsDamageHandler script/component, multiply the chance to receive damage by 2 (cutting the chance in half) ONLY if the current child is tagged as the leader.
Given all of that, you actually give the leader a higher chance to be hit, and you reset that hit chance every time you do the while loop, so that it never gets reduced and the leader will always have a 50/50 chance of taking damage.
Also, while I don't know how you're using this or how the game mechanics work, but I'm curious why the current child would take the full amount of damage instead of only 20% of it.