2014-02-05 105 views
2

如何在Unity中使用SetActiveRecursively(Moment = 1秒)創建閃爍的對象。Unity中閃爍的GameObject

我的例子(更改):

public GameObject flashing_Label; 

private float timer; 

void Update() { 

while(true) 
{ 
flashing_Label.SetActiveRecursively(true); 
timer = Time.deltaTime; 

    if(timer > 1)  
      { 
      flashing_Label.SetActiveRecursively(false); 
      timer = 0;   
      } 
} 

} 
+1

你有一個無限循環。 –

回答

5

使用InvokeRepeating

public GameObject flashing_Label; 

public float interval; 

void Start() 
{ 
    InvokeRepeating("FlashLabel", 0, interval); 
} 

void FlashLabel() 
{ 
    if(flashing_Label.activeSelf) 
     flashing_Label.SetActive(false); 
    else 
     flashing_Label.SetActive(true); 
} 
1

以團結WaitForSeconds功能看看。

通過傳遞int參數。 (秒),你可以切換你的gameObject。

bool fadeIn = true;

IEnumerator Toggler() 
{ 
    yield return new WaitForSeconds(1); 
    fadeIn = !fadeIn; 
} 

然後通過StartCoroutine(Toggler())調用此函數。

1

可以使用協同程序和新的統一4.6 GUI實現這一目標變得非常容易。查看這裏僞造文本的文章。您可以輕鬆地修改它的遊戲物體容易

Blinking Text - TGC

如果你只需要代碼,在這裏你去

using UnityEngine; 
using System.Collections; 
using UnityEngine.UI; 
using UnityEngine.EventSystems; 

public class FlashingTextScript : MonoBehaviour { 
Text flashingText; 
void Start(){ 
//get the Text component 
flashingText = GetComponent<Text>(); 
//Call coroutine BlinkText on Start 
StartCoroutine(BlinkText()); 
} 
//function to blink the text 
public IEnumerator BlinkText(){ 
//blink it forever. You can set a terminating condition depending upon your requirement 
while(true){ 
//set the Text's text to blank 
flashingText.text= ""; 
//display blank text for 0.5 seconds 
yield return new WaitForSeconds(.5f); 
//display 「I AM FLASHING TEXT」 for the next 0.5 seconds 
flashingText.text= "I AM FLASHING TEXT!"; 
yield return new WaitForSeconds(.5f); 
} 
} 
} 

PS:雖然這似乎是一個無限循環,其通常被認爲是一個糟糕的編程習慣,在這種情況下,它的運行效果非常好,因爲一旦物體被破壞,MonoBehaviour就會被銷燬。此外,如果您不需要永久閃爍,則可以根據您的要求添加終止條件。