0
votes

I am trying to make an [ExecuteInEditMode] script spawn game objects (linked to the same prefab) at specific positions right in the Editor so that I can quickly create different hexagon tile maps by just triggering booleans in the inspector. However, the Resources.Load() method cannot not find the prefab even though the path is correct and so I get the following error:

NullReferenceException: Object reference not set to an instance of an object.

Here is the code:

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;
    }

}


If I drag the prefab onto the serialized field of each created tile manually in the inspector instead of trying to load it, everything works fine.

1

1 Answers

3
votes

The asset has to be in a "Resources" folder. So to solve your problem you can put "Tile.prefab" into the folder "Assets/Resources" and use the relative path: Resources.Load("Tile.prefab");

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