using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class NewBehaviourScript : MonoBehaviour
{
public TextMeshProUGUI countText;
private int count;
void Start()
{
count = 0;
SetCountText();
}
void SetCountText()
{
countText.text = $"Score: {count}";
}
}
訪問countText觸發 NullReferenceException。沒有一個解決方案提供在線作業。更可疑的是代碼取自官方統一教程。我想有人弄錯了。
一些附加資訊: 統一 ui CountText 設定中的外觀
一切似乎都井然有序。
uj5u.com熱心網友回復:
unity 提供的Debug類是一個有用的工具,應該在你的游戲開發程序中廣泛使用。
Debug.Log($"My object is {myObject}");
一些參考是在設計時使用Inspector視窗設定的。這些參考必須在進入播放模式之前設定,否則它們將是null. 您可以通過將該型別的物件拖動到檢查器中的物件欄位來設定參考。
當您嘗試訪問空物件的成員時,將發生空參考。
public class DisplayPlayerName : MonoBehaviour
{
public TextMeshProUGUI uiName;
public GameObject player;
void Start()
{
uiName.text = player.name; // <- whoops! NullReferenceException
}
}
在上面的示例中,如果在檢查器中設定uiName或未player設定,則會拋出空參考例外。這是因為我們正在訪問每個物件的成員。我們想將textuiName 的name屬性設定為 player 的屬性。
但是我們怎么知道是哪一個游戲物件導致了問題呢?我有一百萬個游戲物件,不想全部檢查!
幫助縮小搜索范圍的技巧
除錯引發例外的物件的名稱。
if (player == null ||
uiName == null) // <- do some null checking
{
Debug.Log($"{name} has null player or ui"); // <- log the gameobjects name
return; // <- exit the function
}
// This won't throw the exception anymore because we exit the function when null is detected
//
uiName.text = player.name;
當我們以有意義的方式命名每個物件(或至少是最重要的物件)時,記錄物件名稱最有幫助。
您可以將場景中的物件過濾為具有特定組件的物件。使用Hierarchy視窗中的搜索欄,鍵入t:后跟組件的名稱,例如。t:DisplayPlayerName. 這將僅顯示附加了該組件的物件。
希望這為您提供了一些用于統一除錯的新工具。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432341.html
