所以假設我們有一個帶有 Transform 屬性的 MonoBehaviour 類:
public class Class : MonoBehaviour
{
public Transform Target; //An object is already referenced here.
}
問題很簡單:如果這個物件被洗掉(外部),有沒有辦法獲取事件或某種回呼?
Unity 會將其顯示為“缺失”:

因為它只是一個變換,所以你不能OnDestroy()在這里真正使用,即使你可以使用,這也不是一個好的選擇,因為有多少個變換實體。
uj5u.com熱心網友回復:
可在運行時通過編輯器檢查器更改可序列化欄位,因此無法保證編譯時。
根據建議,您可以執行以下操作:
void OnValidate() {
if (Target == null)
throw new NullReferenceException();
}
您也可以嘗試,靈感來自檔案示例(未除錯):
using UnityEngine;
using System.Collections;
using UnityEditor;
// Creates a custom Label on the inspector for all the scripts named ScriptName
// Make sure you have a ScriptName script in your
// project, else this will not work.
[CustomEditor(typeof(Class))]
public class ClassEditor: Editor
{
Class classInstance;
protected void OnEnable() {
classInstance = (Class)target;
}
public override void OnInspectorGUI()
{
//you can first try only uncommenting line below to check if this script is working
//GUILayout.Label ("This is a Label in a Custom Editor");
if (classInstance.Target === null) {
EditorUtility.DisplayDialog("Target transform missing");
}
}
}
不確定Class名稱是否會引起沖突,如果是,請更改類名稱。也不確定組件是否null在缺失時被評估(空值和缺失值不相同),我認為代碼方面是相同的,并且兩者都拋出了 nullRef 例外,但是如果它為空,你會在控制臺中被告知或失蹤。
你可以試試看。希望它至少可以給你。最終的問題留給作業:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385944.html
上一篇:如何使用腳本統一更改相機
下一篇:碰撞器和聲音
