How to infinite loop numbers in while loops? (Unit

2019-08-29 12:14发布

function OnMouseDown () {
    rotationNumber +=1;
}

function Update () {
    while (rotationNumber == 1) {
        gameObject.GetComponent(SpriteRenderer).sprite = leftArrow;
        return;
    } 
    while (rotationNumber == 2) {
        gameObject.GetComponent(SpriteRenderer).sprite = upArrow;
        return;
    }
    while (rotationNumber == 3) {
        gameObject.GetComponent(SpriteRenderer).sprite = rightArrow;
        return;
    }
    while (rotationNumber == 4) {
        gameObject.GetComponent(SpriteRenderer).sprite = upArrow;
        rotationNumber = 1;
        return;
    }
}

I want to loop this but when I click it the fourth time it just goes straight to the first image. I tried yield WaitForSeconds but it didn't work.

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-29 12:51

The problem is that you are setting rotationNumber to 1 inside the while loop. Do it in this way:

function OnMouseDown () {
    rotationNumber += 1;
    if ( rotationNumber > 4 ) rotationNumber = 1;
}

function Update () {
    while (rotationNumber == 1) {
        gameObject.GetComponent(SpriteRenderer).sprite = leftArrow;
        return;
    } 
    while (rotationNumber == 2) {
        gameObject.GetComponent(SpriteRenderer).sprite = upArrow;
        return;
    }
    while (rotationNumber == 3) {
        gameObject.GetComponent(SpriteRenderer).sprite = rightArrow;
        return;
    }
    while (rotationNumber == 4) {
        gameObject.GetComponent(SpriteRenderer).sprite = upArrow;
        return;
    }
}
查看更多
在下西门庆
3楼-- · 2019-08-29 12:58

I'm not quite sure why you are using a while loop within in an update loop, but try this below. Every time you click the rotation number increases and the sprite is changed until the rotationNumber variable is > 4 in which case it resets the variable back to 1.

function Update()
{
    if(rotationNumber == 1)
    {
         gameObject.GetComponent(SpriteRenderer).sprite = leftArrow;
    }else if(rotationNumber ==2)
    {
         gameObject.GetComponent(SpriteRenderer).sprite = upArrow;  
    }else if(rotationNumber ==3)
    {
         gameObject.GetComponent(SpriteRenderer).sprite = rightArrow;
    }else if(rotationNumber == 4)
    {
        gameObject.GetComponent(SpriteRenderer).sprite = upArrow;  
    }else if(rotationNumber > 4)
    {
        rotationNumber = 1;
    }
}
查看更多
登录 后发表回答