我一直在使用 Unity 創建一個簡單的 2D 游戲,但問題是即使游戲物件“玩家”被破壞,游戲物件“isDead”(文本)也不會出現。
這是我的腳本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class youDied_Text : MonoBehaviour
{
private Transform player;
private Text isDead;
// public static bool isDead;
// Start is called before the first frame update
private void Start() {
isDead = GetComponent<Text>();
}
void checkForDeath()
{
if (player==false)
{
isDead.gameObject.SetActive(true);
}
else
{
isDead.gameObject.SetActive(false);
}
}
// Update is called once per frame
void Update()
{
player = GameObject.FindWithTag("Player").transform;
checkForDeath();
}
}
該腳本附加在我需要在 UI 元素中顯示的文本中。
uj5u.com熱心網友回復:
正如目前所指出的,你會得到一個
NullReferenceException絕對不是你想要的。實際上根本不需要/冗余
Transform。只需存盤GameObject參考即可您當前正在將物件設定為非活動狀態,該物件已
Text附加...這與您的組件所附加的物件相同!=>一旦您將其設定為非活動狀態,就在第二種情況下結束=>從現在開始
Update不再呼叫!
一般來說,這聽起來應該只發生一次,我會使用更多事件驅動的方法,并在你的播放器上有一個組件,例如
public class Player : MonoBehaviour
{
public UnityEvent onDied;
private void OnDestroy ()
{
onDied.Invoke();
}
}
然后只需將偵聽器/回呼附加到該事件一次,而無需輪詢檢查狀態。您可以直接通過 Inspector 執行此操作(就像在 Button.onClick 中一樣),也可以通過代碼例如
public class youDied_Text : MonoBehaviour
{
// Already reference things via the Inspector if possible!
[SerializeField] private GameObject player;
[SerializeField] private Text isDead;
private void Awake()
{
if(!isDead) isDead = GetComponent<Text>();
isDead.gameObject.SetActive(false);
// If you want to rather set it via the Inspector remove all the rest here
//if(!player) player = GameObject.FindWithTag("Player"). GetComponent<Player>();
// or even simpler
if(!player) player = FindObjectOfType<Player>();
player.onDied.AddListener(OnPlayerDied);
}
// If you want to rather set it via the Inspector make this public
private void OnPlayerDied()
{
isDead.gameObject.SetActive(true);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/428500.html
上一篇:忽略所有物件的碰撞
