【发布时间】:2021-01-25 05:51:03
【问题描述】:
我正在尝试在编辑器中的特定位置创建一个 [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;
}
}
如果我在检查器中手动将预制件拖到每个创建的图块的序列化字段上,而不是尝试加载它,那么一切正常。
【问题讨论】: