首页 > 解决方案 > 无法在 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;
    }

}


如果我在检查器中手动将预制件拖到每个创建的图块的序列化字段上,而不是尝试加载它,那么一切正常。

标签: c#unity3d

解决方案


资产必须位于“资源”文件夹中。因此,要解决您的问题,您可以将“Tile.prefab”放入文件夹“Assets/Resources”并使用相对路径:Resources.Load("Tile.prefab");

https://docs.unity3d.com/ScriptReference/Resources.Load.html


推荐阅读