這個問題在這里已經有了答案: 什么是 NullReferenceException,我該如何解決? (27 個回答) 12 小時前關閉。
我正在 Unity 中開發一個簡單的小游戲,其目標是使用浮動手將球引導到籃筐中,每次球進入籃筐時,由于籃筐內帶有觸發器的隱藏對撞機,游戲會重置.
我正在嘗試實作的功能:
每次球進入籃筐時,text.UI 都會更新以反映您的新得分,從 0 分開始,每次扣籃得分增加 1。
問題:
如何將“Debug.Log”轉換為 text.UI?
我只是在 Unity 控制臺上成功更新了分數,我無法將這些事件轉換為 text.UI。我創建的 text.UI 游戲物件只顯示文本“新游戲”并且永遠不會更新。
更新:我創建了一個新腳本來解決此問題,但出現此錯誤:
NullReferenceException:物件參考未設定到物件的實體ChangingText.Start ()(在Assets/Scripts/ChangingText.cs:12)
程序:
1. 創建游戲物件和腳本以在場景重新啟動后保留資料。
我已經創建了一個腳本來在重新啟動同一個場景后保持分數,我只有一個場景。 我已將此腳本附加到游戲物件:“GameController”,這就是保持分數更新的方式。
場景名稱是:
《扣籃練習》
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameControl : MonoBehaviour
{
// Giving it a name called "Control", any other script can interact with it
public static GameControl Control;
public int score;
// Called before Start()
private void Awake()
{
// If there's a control already, delete this
// If there's no control, make this the control object
if (Control == null)
{
Control = this;
DontDestroyOnLoad(gameObject); // Don't destory the object when a scene is loaded
}
else if (Control != this)
{
Destroy(gameObject);
}
}
}
我已經包含的影像來證明這一點:
創建“GameController”游戲物件和腳本
2.在籃子內創建一個隱藏的觸發碰撞游戲物件,腳本內有一個scenemanager.loadscene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class RestartTrigger : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Ball")
{
SceneManager.LoadScene(0);
}
}
}
我已經包含的影像來證明這一點:
創建觸發器碰撞器并重新啟動觸發器
3. 創建一個腳本來保持分數并將這個組件添加到前面提到的觸發器碰撞器中
請注意,該腳本參考了我之前創建的游戲控制腳本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeepingScore : MonoBehaviour
{
static void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Ball")
{
GameControl.Control.score ;
if (GameControl.Control.score == 1)
{
Debug.Log("You have " GameControl.Control.score " point");
}
else if (GameControl.Control.score != 1)
{
Debug.Log("You have " GameControl.Control.score " points");
}
}
}
}
這是我添加的另一張圖片:
創建腳本以保持分數并將其附加到觸發欄位
4. 在螢屏上創建一個 Text.UI 并創建一個新腳本來更改文本,只為出現錯誤
這是產生 NullReferenceException 錯誤的腳本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangingText : MonoBehaviour
{
public Text scoreText;
void Start()
{
scoreText.text = GameControl.Control.score.ToString();
}
}
這是另一個要演示的影像:
創建文本物件
這是我制作的螢屏錄像,用于展示我的場景目前的樣子:
https://www.screencast.com/t/JUBsUkHuHgHC
你有什么建議嗎?
謝謝
uj5u.com熱心網友回復:
如果您的實體之一為空并且您嘗試修改它,則會發生 NullReferenceException,在日志錯誤中,它表明:
物件參考未設定為物件的實體ChangingText.Start()
這意味著您的 scoreText 實體未連接到任何 UI,并且為空。要解決這個問題,只需簡單地創建文本 UI 游戲物件并將其拖到使用更改文本腳本分配的物件中的“scoreText”欄位中
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322896.html
