Hey all, simple question, I have a for loop to deal damage but I need it to keep running rather than run through it once. Here’s my code:
public void TakeDamage(int shots, int damagePerShot)
{
Debug.Log(shots + " " + damagePerShot);
for (int s = 0; s < shots; s++)
{
ModelController modelController = transform.GetChild(s).GetComponent<ModelController>();
modelController.currentWounds -= damagePerShot;
if (modelController.currentWounds <= 0)
{
Destroy(modelController.gameObject);
}
else
{
}
}
}
so the unit that is taking the damage (and has this script) has a number of children objects that will be the parts that actually take the damage. If the shots is let’s say 4, and the damagePerShot is 2, and let’s just say the health of each child object is 3, then I want this script to run through the for loop (dealing 2 damage) and if the health is above 0 (it should be 1 now) go back through the for loop rather than move to the next “s” or model in the unit. I assume it should be within the else part of the if statement.
Any thoughts would be great!
I think what you’re actually looking for is not to “keep the for loop going” but to always have the damage get applied to the first still living child? You still want “shots” number of shots to happen.
Yes that would be accurate. How do I make that happen?
I would do something like this:
ModelController FindNextLivingModel(Transform parent, int startAt) {
ModelController found = null;
for (int i = startAt; i < parent.childCount; i++) {
var child = parent.GetChild(i);
ModelController childController = child.GetComponent<ModelController>();
if (childController != null && childController.currentWounds > 0) {
found = childController;
break;
}
}
return found;
}
public void TakeDamage(int shots, int damagePerShot) {
int currentModelIndex = 0;
ModelController current = FindNextLivingModel(transform, currentModelIndex++);
for (int s = 0; s < shots && current != null; s++) {
current.currentWounds -= damagePerShot;
if (current.currentWounds <= 0) {
Destroy(current.gameObject);
current = FindNextLivingModel(transform, currentModelIndex++);
}
}
}
Simple solution, just changed the GetChild(s) to GetChild(0) and it seems to work
Are you sure you’re not just always hitting the first child then? Even if you Destroy something it doesn’t go away until the end of the frame.
Yeah I wrote that one before I saw your example posted, which I need to try. It doesn’t remove the 0 child so it won’t work my way. Let me try yours
Just a heads up I wrote that off the cuff and didn’t test it or anything. There’s a chance it won’t even compile
So far it seems to be working!