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 *== 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?

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 *== 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;