C#(Unity) - 如何停止函数执行?

时间:2017-01-22 18:32:04

标签: c# unity3d unity5

我有这样的代码:

    public void Interacted(){
    if (GameObject.Find ("Sara").GetComponent<controls> ().isIntered) {
        if (Interer.name == "sinkTop" && !sinked) {
            Interer.GetComponent<SpriteRenderer> ().sprite = sinkON;
            sinked = true;
        }
        if (Interer.name == "sinkTop" && sinked) {
            Interer.GetComponent<SpriteRenderer> ().sprite = sinkOFF;
            sinked = false;
        }
    }
}

如何在Interacted()内停止if (Interer.name == "sinkTop" && !sinked)执行?

1 个答案:

答案 0 :(得分:2)

return内的末尾添加if

if (Interer.name == "sinkTop" && !sinked) 
{
    Interer.GetComponent<SpriteRenderer> ().sprite = sinkON;
    sinked = true;
    return;         //return here.
}

或在第二个else之前添加if

if (Interer.name == "sinkTop" && !sinked) 
{
    Interer.GetComponent<SpriteRenderer> ().sprite = sinkON;
    sinked = true;
}
else if (Interer.name == "sinkTop" && sinked) 
{
    Interer.GetComponent<SpriteRenderer> ().sprite = sinkOFF;
    sinked = false;
}

此外,您可以重构代码:

if (Interer.name == "sinkTop") 
{
    if (sinked)
    {
        Interer.GetComponent<SpriteRenderer> ().sprite = sinkOFF;
        sinked = false;
    }
    else
    {
        Interer.GetComponent<SpriteRenderer> ().sprite = sinkON;
        sinked = true;
    }
}