我無法弄清楚為什么播放器腳本附加到的物件的轉換回傳 null。
這是控制器代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
Player player = new Player();
void Start()
{
player.SetEndpos(new Vector3(0f, 0f, 0f));
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
int roll = Random.Range(1, 7);
player.SetEndpos(new Vector3(roll, 0f, 0f));
}
player.Run();
}
}
這是播放器代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Vector3 endPos = new Vector3(0f, 0f, 0f);
public void Run()
{
if (transform.position != null)
{
transform.position = endPos;
if (endPos != new Vector3(0f, 0f, 0f))
{
Debug.Log($"pos was set to: {endPos}");
}
}
}
public Vector3 GetEndpos()
{
return endPos;
}
public void SetEndpos(Vector3 end)
{
endPos = end;
Debug.Log($"endPos = {endPos}");
}
}
空錯誤在“transform.position = endPos;”處給出 在播放器和“player.Run();”中 在控制器中
確切的錯誤訊息:NullReferenceException Player.Run () (at Assets/Scripts/Player.cs:11) Controller.Update() (at Assets/Scripts/Controller.cs:20)
影像: 管理器物件具有控制器腳本
影像: 播放器物件具有播放器腳本
我確定這是我犯的一些愚蠢的錯誤,但我無法在網上的其他任何地方找到解決方案。
uj5u.com熱心網友回復:
您需要做的是Player player = new Player();用
public Player player;
或替換該行
[Serializable]
private Player player;
在您的控制器腳本中。
之后,您將在控制器的檢查器視窗中看到更改。應該有一個空欄位,上面寫著“無(玩家)”。
將您的PlayerGameObject 放入您的層次結構中,并將其拖到空欄位內的空欄位中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322894.html
