当前正在处理Unity项目,并且遇到了一个问题,即对象没有被销毁。子对象只是2个图像,而文本对象则没有其他脚本。有时,对象已被正确删除,但其他时候则没有。谁能看到为什么呢? MEC代替了统一协同程序,但Unity协同程序也出现了问题,这是我第一次尝试修复它。
该问题似乎在负载下更多发生。
using MEC;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
[RequireComponent(typeof(CanvasGroup))]
public class UINotificationEffect : MonoBehaviour
{
// Private
private CanvasGroup canvas_group;
private float time_passed;
private bool fading_out;
// Public
public float alive_time = 3.0f;
public float fade_time = 0.5f;
public string message = "Notification message";
private void Awake()
{
canvas_group = GetComponent<CanvasGroup>();
canvas_group.alpha = 0;
}
private void Start()
{
gameObject.GetComponentInChildren<TextMeshProUGUI>().text = message;
Timing.RunCoroutine(FadeTo(1.0f, fade_time), gameObject);
}
private void Update()
{
// At alive time end, fade out and get rid of this gameobject
time_passed += Time.deltaTime;
if (time_passed >= alive_time && !fading_out)
{
Timing.RunCoroutine(FadeTo(0.0f, fade_time), gameObject);
fading_out = true;
}
// Destroy gameobject after alive time + fade time is over.
if (fading_out && canvas_group.alpha <= 0.02f)
{
Timing.KillCoroutines(gameObject);
Destroy(gameObject, 1f);
}
}
/// <summary>
/// Fade alpha of the canvas group in a certain direction (controlled by alpha_value).
/// </summary>
/// <param name="alpha_value">Fade to full (1.0) or fade to nothing (0.0)?</param>
/// <param name="transition_time">The fading time of the alpha.</param>
/// <returns></returns>
IEnumerator<float> FadeTo(float alpha_value, float transition_time)
{
if (gameObject != null && gameObject.activeInHierarchy)
{
float alpha = canvas_group.alpha;
for (float t = 0.0f; t <= 1.0f; t += Time.deltaTime / transition_time)
{
canvas_group.alpha = Mathf.Lerp(alpha, alpha_value, t);
yield return Timing.WaitForOneFrame;
}
}
yield break;
}
/// <summary>
/// Update the text that should be displayed.
/// </summary>
/// <param name="text">The new message.</param>
public void UpdateText(string text)
{
message = text;
gameObject.GetComponentInChildren<TextMeshProUGUI>().text = message;
}
/// <summary>
/// Stop all coroutines when the gameobject is destroyed.
/// </summary>
private void OnDestroy()
{
//StopAllCoroutines();
}
}
答案 0 :(得分:2)
您无法保证FadeTo
中的循环运行时t
大约等于1f
(实际上,您只知道它将循环运行至少一次) t = 0f
)。因此,您的alpha值永远不会低于0.2f
,在这种情况下,永远不会调用Destroy
。
在渐变循环的末尾添加一行以将canvas_group.alpha
精确设置为alpha_value
:
IEnumerator<float> FadeTo(float alpha_value, float transition_time)
{
if (gameObject != null && gameObject.activeInHierarchy)
{
float alpha = canvas_group.alpha;
for (float t = 0.0f; t <= 1.0f; t += Time.deltaTime / transition_time)
{
canvas_group.alpha = Mathf.Lerp(alpha, alpha_value, t);
yield return Timing.WaitForOneFrame;
}
canvas_group.alpha = alpha_value;
}
yield break;
}