我需要幫助,拜托。我只需要制作閃爍的 2Dlight(使用 Unviversal Pipeline)。一段時間后,燈光開始閃爍并恢復到原來的值(light.intensivity = 0.36f),一段時間后他又開始閃爍。但是對于這個糟糕的代碼,我不能這樣做,閃爍只會起作用,因為每次重新啟動協程(StartCoroutine(LightFlicker());在協程中)。但我不知道如何制作這個東西了。也許使用另一種方法來閃爍燈光?
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering.Universal;
using UnityEngine.Experimental;
using UnityEngine.Experimental.Rendering.LWRP;
public class FlickeringLight : MonoBehaviour {
public UnityEngine.Experimental.Rendering.Universal.Light2D renderLight;
public AudioSource AS; // AudioSource to play the audio.
public AudioClip LightAudio; // Audio to play.
[SerializeField] float firstValue = 0f;
[SerializeField] float secondValue = 0.36f;
[SerializeField] float secondsBetweenFlickers = 2f;
void Start ()
{
renderLight.intensity = renderLight.intensity;
StartCoroutine(LightFlicker());
}
private void Awake()
{
renderLight = GetComponent?<UnityEngine.Experimental.Rendering.Universal.Light2D?>();
}
IEnumerator LightFlicker()
{
renderLight.intensity = Random.Range(firstValue, secondValue);
yield return new WaitForSeconds(secondsBetweenFlickers);
AS.PlayOneShot(LightAudio); // Play the audio.
StartCoroutine(LightFlicker());
}
//failed try to pause Coroutine LightFLicker
/* IEnumerator TimerLight()
{
StopCoroutine(LightFlicker());
renderLight.intensity = 0.36f;
yield return new WaitForSeconds(3f);
StartCoroutine(LightFlicker());
}
*/
}```
uj5u.com熱心網友回復:
添加一個while回圈以永不停止協程
IEnumerator TimerLight()
{
while (true)
{
renderLight.intensity = Random.Range(firstValue, secondValue);
yield return new WaitForSeconds(secondsBetweenFlickers);
}
}
然后,如果您愿意,可以嘗試隨機等待時間
IEnumerator TimerLight()
{
while (true)
{
renderLight.intensity = Random.Range(firstValue, secondValue);
var randomTime = Random.Range(0, secondsBetweenFlickers);
yield return new WaitForSeconds(randomTime);
}
}
也許您有時需要某種移動平均線來使其平滑。
private Queue<float> queue; // TODO: initialize
private int smoothing = 5;
IEnumerator TimerLight()
{
var sum = 0f;
while (true)
{
while (queue.Count > smoothing)
{
sum -= queue.Dequeue();
}
var newValue = Random.Range(firstValue, secondValue);
queue.enque(newValue);
sum = newValue;
renderLight.intensity = sum / queue.Count;
yield return new WaitForEndOfFrame();
}
}
我還沒有測驗過這段代碼,但它應該幾乎可以正常作業。因為我以前用這個移動平均佇列來統一閃爍燈光。我認為它正在運行每一幀......
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439963.html
下一篇:統一碰撞
