[英]I get a NullReferenceException error when trying to use Tilemap.GetTile in unity
I have my code set up so that when the spacebar is clicked, the console prints out the current tile the player is on.我设置了我的代码,以便在单击空格键时,控制台会打印出播放器所在的当前图块。 However, I get this long error instead.
但是,我得到了这个长错误。 Can someone please tell me how to fix this and/or why this is happening?
有人可以告诉我如何解决这个问题和/或为什么会这样吗? This is the error:
这是错误:
NullReferenceException UnityEngine.Tilemaps.Tilemap.GetTileAsset (UnityEngine.Vector3Int position) <0x3886fc90 + 0x0005a> in :0 UnityEngine.Tilemaps.Tilemap.GetTile (UnityEngine.Vector3Int position) (at C:/buildslave/unity/build/Modules/Tilemap/ScriptBindings/Tilemap.bindings.cs:113) Player.Dig () (at Assets/Scripts/Player.cs:56) Player.Update () (at Assets/Scripts/Player.cs:28)
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)
My code is:我的代码是:
private void Dig()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Vector3Int playerPos = grid.WorldToCell(player.transform.position);
Tilemap tilemap = new Tilemap();
Debug.Log(tilemap.GetTile(playerPos));
}
}
The code is in a method that runs in update.该代码位于更新中运行的方法中。
Tilemap
is a Component
and as every other Component
should never be created using new
! Tilemap
是一个Component
,并为所有其他Component
不应该使用创建new
! This is forbidden in Unity.这在 Unity 中是被禁止的。 A
Component
can only exist attached to a GameObject
eg using AddComponent
or by Instantiate
a prefab with the components attached.一个
Component
只能存在于附加到一个GameObject
例如使用AddComponent
或通过Instantiate
一个带有附加组件的预制件。
Best way however would be to Create a Tilemap already in the Editor and either use it directly or store it as prefab.然而,最好的方法是在编辑器中 创建一个 Tilemap并直接使用它或将其存储为预制件。
Then you can reference it in a field like eg然后你可以在一个字段中引用它,例如
public Tilemap tilemap;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.