- Home /
C# while within foreach doesn't complete
Hi,
I'm iterating through objects within a sphere (Physics.OverlapSphere). There are two types of objects found (parent and child). If a parent is found a while loop is triggered to find the distance to it's child objects. These distances needs to be concatenated into a string. (for network optimization). The problem is that the values are not concetenated but spit out separately.
Expected Debug.Log() output:
/ 0 / 50 / 1 / 48.5 / 2 / 11 / 3 / 15
Result
/ 0 / 50
/ 1 / 48.5
/ 2 / 11
/ 3 / 15
I already placed the while loop in a coroutine, but with no result. I stripped the code down to a bare minimum. I'd appreciate a fresh look on this!
using UnityEngine;
using System.Collections;
public class tester : MonoBehaviour {
private float radius = 100.0F;
private int nrOfObects = 5;
private int objectCounter = 0;
public void FixedUpdate() {
foreach (Collider collider in Physics.OverlapSphere(transform.position, radius)) {
StartCoroutine( combineValues( collider ) );
}
}
IEnumerator combineValues( Collider collider ){
string combinedValues = "";
while (objectCounter < nrOfObects) {
if (collider.name == this.name + "_child_" + objectCounter) {
float distance = Vector3.Distance(transform.position, collider.transform.position);
combinedValues += " / "+objectCounter.ToString()+" / "+distance.ToString();
objectCounter++;
}
}
Debug.Log (combinedValues);
yield return null;
}
}
You have an if statement inside your while loop, if it does not evaluate to true it will never increment the objectCounter value which means it will continue to be false because nothing has changed and the while loop will not end.
Thank you for your reply, The if evaluating false is not the case, the objects are found and the counter is incrementing as you can see in the "expected debug.log() output". $$anonymous$$y problem is that the Debug.Log() is triggered before the while loop is done
Answer by supericecream · Sep 04, 2014 at 01:33 PM
Probably because that the code IS in the coroutine. Put it in a normal function and return the finished string, then Debug.Log the returned value.
Answer by yourulenl · Sep 04, 2014 at 01:53 PM
Found it. the string combinedValues = "";
should be above the initialization of the foreach colider loop. In this case it gets reset on each found colider