c# - 无法在 Unity 编辑器中加载预制件
问题描述
我正在尝试在编辑器中的特定位置制作一个 [ExecuteInEditMode] 脚本生成游戏对象(链接到同一个预制件),这样我就可以通过在检查器中触发布尔值来快速创建不同的六边形瓷砖贴图。但是,即使路径正确,Resources.Load() 方法也找不到预制件,因此出现以下错误:
NullReferenceException:对象引用未设置为对象的实例。
这是代码:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class PositionChecker : MonoBehaviour
{
[SerializeField] float tileGap = 1.5f;
[SerializeField] GameObject tilePrefab; // alternatively tried dragging the prefab in the field in the inspector - it worked
[SerializeField] bool tileUpLeft;
GameObject tilesParent;
private void Awake()
{
tilesParent = GameObject.Find("All Tiles");
tilePrefab = Resources.Load("Assets/Prefabs/Tile.prefab") as GameObject;
}
// Update is called once per frame
void Update()
{
CheckForCreateTile();
}
private void CheckForCreateTile()
{
if (tileUpLeft)
{
tileUpLeft = false;
InstantiateTilePrefab(new Vector3(transform.position.x - 0.6f * tileGap, transform.position.y, transform.position.z - tileGap));
}
}
private void InstantiateTilePrefab(Vector3 vector3)
{
GameObject newTile = PrefabUtility.InstantiatePrefab(tilePrefab, tilesParent.transform) as GameObject;
Debug.Log(tilePrefab); // null
Debug.Log(tilesParent); // ok
Debug.Log(newTile); // Null
newTile.transform.position = vector3;
}
}
如果我在检查器中手动将预制件拖到每个创建的图块的序列化字段上,而不是尝试加载它,那么一切正常。
解决方案
资产必须位于“资源”文件夹中。因此,要解决您的问题,您可以将“Tile.prefab”放入文件夹“Assets/Resources”并使用相对路径:Resources.Load("Tile.prefab");
https://docs.unity3d.com/ScriptReference/Resources.Load.html
推荐阅读
- mysql - 如何用group by计算每行的字符数
- python - 在python中一次重新缩放多个变量
- php - Laravel Auth Guard 自定义尝试总是返回 null
- azure-storage - 帐户之间的 Azure 存储复制 - 按什么顺序?
- php - Zend 框架的版本是多少?
- ssl - 端到端加密 Nginx Ingress 控制器和 AWS NLB
- html - 在具有溢出属性的 div 内移动滚动部分
- python - 如何使所有条件(if,elif,else)在for循环中工作,在Python中使用try except
- c++ - “cc1plus: error: bad value ('tigerlake') for '-march=' switch” 编译错误
- mysql - 如何将选择查询设置为变量并在mysql的另一个选择查询中使用它