- Home /
Converting foreach touch into for.
Hi. I read that the "foreach" can cause lag on phones
foreach (Touch touch in Input.touches)
This method should work better(forgot why)
for (int i = 0 ; i < firstArray.lenght ; i++)
firstArray[i].something = something else//modify...
I've been trying to convert this code that handles touch, into using the for statement instead of foreach but without success
Here's the code that I need to change:
if(Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
Vector3 inputGuiPosition = touch.position;
inputGuiPosition.y = Screen.height - inputGuiPosition.y;
if(inputGuiPosition.x > Screen.width / 5)
{
_jump = true;
}
}
}
Answer by KellyThomas · Feb 02, 2014 at 01:06 AM
for (int i = 0 ; i < Input.touches.Length; i++) {
Vector3 inputGuiPosition = Input.touches[i].position;
// ....
}
"This method should work better(forgot why)"
The indexed for loop has minor performance advantages under some circumstances.(irrelevant, disregard)
Inside of the loop you have the counter "`i`" so we know the current index. (essential for some algorithms)
Can be used to iterate/count arbitrarily. (foreach can only process IEnumerable)
I find the simplified syntax makes foreach
a better choice for iterating over an collection.
the only bad thing about this one, is that you would need to add extra code to know which finger you are tracking, Touch.FingerId, since the touches array is not always the same but, good answer +1
Your answer
Follow this Question
Related Questions
C# For loop in button to set gameObjects in array to active 1 Answer
For loop does not loop C# 2 Answers
foreach (or for-next loop) not updating local values 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers