- Home /
Division in loop not working
I am trying to spawn 3 GameObjects around another GameObject with equal spacing between them. So far I have this:
var i : float;
for(i = 0; i < 3; i++){
var rot : float;
var spawnPos : Vector3;
rot = ((i+1/3) * (Mathf.PI * 2));
Debug.Log(i);
Debug.Log(rot);
spawnPos = new Vector3(5*Mathf.Cos(rot) + transform.position.x,
5*Mathf.Sin(rot) + transform.position.y,
transform.position.z);
var g : GameObject = Instantiate(gunPreFab, spawnPos, Quaternion.identity);
guns.Add(g.gameObject);
}
The variable "i" is being increased every loop cycle, however, "rot" never becomes anything other than zero. I am not sure at all why this is occurring.
If I run this:
function Start() {
var i : float;
for (i=0; i<3; i++) {
var rot : float;
rot = ((i+1/3) * ($$anonymous$$athf.PI * 2));
Debug.Log(rot);
}
}
I get 0, 6.3, 12.6.
Good catch. The 1/3 will always evaluate to 0, but he's not getting 0 every time through the loop.
Answer by robertbu · Oct 30, 2013 at 01:07 AM
Try this:
rot = ((i+1.0/3.0) * (Mathf.PI * 2.0));
You were doing integer division.
This solves the problem of the rotation, but the spawning position always equals the same thing, no matter what "rot" is.
You are multiplying by 2 * #PI, so the result will always be the same rotation. That is, 2.09, 8.378, and 14.66 all represent the same end angle.
Okay, so I'm doing my math wrong? What I'm trying to achieve is that the angle of rotation on them are 1/3 of 2(PI), 2/3 of 2(PI), and 2(PI), but apparently it's doing the first one fine and multiplying the rest by 2?
You want to multiply:
rot = ((i*1.0/3.0) * ($$anonymous$$athf.PI * 2.0));
Your answer
![](https://koobas.hobune.stream/wayback/20220613120911im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Nested for-loop freezing Unity 1 Answer
Turning On & Off Renderers 1 Answer
Creating a looping spawn with an Array 0 Answers
Which Method is Optimal/Fastest - Raycast Vs Collider 3 Answers
How to obtain a gameObject from an List with the name? 1 Answer