![](/img/trans.png)
[英]NullReferenceException error in Unity when trying to get data from a static class
[英]I get a NullReferenceException error when trying to use Tilemap.GetTile in unity
我設置了我的代碼,以便在單擊空格鍵時,控制台會打印出播放器所在的當前圖塊。 但是,我得到了這個長錯誤。 有人可以告訴我如何解決這個問題和/或為什么會這樣嗎? 這是錯誤:
NullReferenceException UnityEngine.Tilemaps.Tilemap.GetTileAsset (UnityEngine.Vector3Int position) <0x3886fc90 + 0x0005a> in :0 UnityEngine.Tilemaps.Tilemap.GetTile (UnityEngine.Vector3Int position) (在 C:/buildslave/buildslave/unTiles/ ScriptBindings/Tilemap.bindings.cs:113) Player.Dig () (at Assets/Scripts/Player.cs:56) Player.Update () (at Assets/Scripts/Player.cs:28)
我的代碼是:
private void Dig()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Vector3Int playerPos = grid.WorldToCell(player.transform.position);
Tilemap tilemap = new Tilemap();
Debug.Log(tilemap.GetTile(playerPos));
}
}
該代碼位於更新中運行的方法中。
Tilemap
是一個Component
,並為所有其他Component
不應該使用創建new
! 這在 Unity 中是被禁止的。 一個Component
只能存在於附加到一個GameObject
例如使用AddComponent
或通過Instantiate
一個帶有附加組件的預制件。
然而,最好的方法是在編輯器中 創建一個 Tilemap並直接使用它或將其存儲為預制件。
然后你可以在一個字段中引用它,例如
public Tilemap tilemap;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.