- Home /
Question by
Toomuchbob · Jan 11, 2013 at 12:04 PM ·
arrayfor loop
For loop to index array storing hundreds of duplicate entries
function UnitSpacesMovement()
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit, 1000))
{
var coordTest : Vector3 = Vector3(Mathf.Round(hit.point.x), Mathf.Round(hit.point.y), Mathf.Round(hit.point.z));
for(var i = 0; i < getSpaces.length; i++)
if(getSpaces[i] == coordTest)
{
return;
}
else
{
getSpaces.length ++;
getSpaces.Add(coordTest);
return;
}
}
}
This function is being called in function Update() and is storing hundreds of duplicate entries while running, can someone explain to me why this isn't working, and why it would store so many of the same variable?
Comment
Answer by Jason_DB · Jan 11, 2013 at 01:42 PM
I think that you're executing the else every time that a your coords don't match a space (within the for loop), instead of checking the entire array first. I would suggest something more like this:
for(var i = 0; i < getSpaces.length; i++){
if(getSpaces[i] == coordTest)
{
return;
}
}
//Since this part won't execute if we found a match, we shouldn't need an if
getSpaces.length ++;
getSpaces.Add(coordTest);
return;