How to infinite loop numbers in while loops? (Unit

2019-08-29 12:27发布

问题:

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.

回答1:

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;
    }
}


回答2:

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;
    }
}