- Home /
forloop running more than said amout of times
i am trying to run a bit of code once, i cant do this at start unfortunately so i tried a for loop, but it did the code multiple times i debug the temporary variable i and it stayed at 0 the whole time so i added the line
i = i + 1
this seemed to add 1 to i but it still ran the code multiple times. I know its not the moveToPos method as when i binded it to a key it worked fine. heres my code:
void Update () {
for (int i = 0; i < 1; i++) {
moveToPos ();
}
}
public void moveToPos(){
startpos = new Vector3 (transform.position.x, transform.position.y - 10);
RaycastHit2D hit2d = Physics2D.Raycast (startpos,Vector2.down);
if (hit2d.collider != null) {
gameObject.transform.position = new Vector3 (gameObject.transform.position.x,
hit2d.collider.gameObject.transform.position.y);
}
}
Comment
Answer by Kishotta · Jul 24, 2017 at 05:33 AM
Do you mean to call moveToPos ()
every frame? If you only want it run once, you should move the call from Update ()
to either Awake ()
or Start ()
.
Then you'll need to wrap your for
loop in a conditional check so that it only fires when you want it to (and the for loop is not actually needed here):
void Update () {
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.Space)) { // As an example
moveToPos ();
}
}