簡體   English   中英

在 Unity 中閃爍游戲對象

[英]Flashing GameObject in Unity

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

我的例子(更改):

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

使用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);
}

看看 unity WaitForSeconds函數。

通過傳遞 int 參數。 (秒),你可以切換你的游戲對象。

布爾淡入=真;

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

然后通過StartCoroutine(Toggler())調用這個函數。

您可以使用協程和新的 Unity 4.6 GUI 輕松實現這一點。 在這里檢查這篇文章,它偽造了一個文本。 您可以輕松地為游戲對象輕松修改它

閃爍文本 - 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 就會被銷毀。 此外,如果您不需要它永遠閃爍,您可以根據您的要求添加終止條件。

簡單的方法是使用 InvokeRepeating() 和 CancelInvoke() 方法。

  1. InvokeRepeating("BlinkText",0,0.3) 將每隔 0.03 時間間隔重復調用 BlinkText()。
  2. CancelInvoke("BlinkText") 將停止重復調用。

這是示例:

//Call this when you want to start blinking
InvokeRepeating("BlinkText", 0 , 0.03f);

void BlinkText() {
    if(Title.gameObject.activeSelf)
        Title.gameObject.SetActive(false);
    else
        Title.gameObject.SetActive(true);
}

//Call this when you want to stop blinking
CancelInvoke("BlinkText");

Unity 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM