2017-01-22 640 views
-4

我有這樣一個代碼:C#(Unity) - 如何停止函數執行?

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

如何停止內部if (Interer.name == "sinkTop" && !sinked)Interacted()執行?

回答

2

末添加returnif

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

或之前第二if添加else

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

LOL。我嘗試過'返回;'之前,它沒有工作,但在你回答後我再次嘗試它,它的工作。無論如何感謝 – Sharpy

+0

@Sharpy,不客氣。 –