【发布时间】:2025-12-10 22:35:01
【问题描述】:
我在初始加载游戏时创建目录结构时遇到问题。我有一个脚本,如果它们不存在,应该创建一组文件夹,但我收到错误:NullReferenceException: Object reference not set to an instance of an object Loader.Start () (at Assets/_Scripts/Managers/Loader.cs:22) 我正在创建一个我想创建的文件夹数组,然后使用 foreach循环遍历数组并使用Directory.CreateDirectory(path) 它应该创建目录,但事实并非如此。我在这里做错了什么?
Loader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class Loader : MonoBehaviour
{
public GameObject gameManager;
// File System List of Folders
private List<string> folders;
private void Awake ()
{
if (GameManager.Instance == null)
Instantiate(gameManager);
}
private void Start()
{
// Create folder List
folders.Add(Application.persistentDataPath + GameManager.animalDataFilePathRoot);
folders.Add(Application.persistentDataPath + GameManager.animalDataFilePathJSON);
folders.Add(Application.persistentDataPath + GameManager.animalDataFilePathTex);
folders.Add(Application.persistentDataPath + GameManager.animalDataFilePathTemp);
// If a folder doesn't exist, create it.
foreach (string folder in folders)
{
CreateDirectory(folder);
}
}
// Create Directory
public void CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
Debug.Log(path + " folder created.");
}
else if (Directory.Exists(path))
{
Debug.Log(path + " folder already exists.");
}
}
}
GameManager 中的变量设置如下:
public static string animalDataFilePathRoot { get; set; }
public static string animalDataFilePathJSON { get; set; }
public static string animalDataFilePathTex { get; set; }
public static string animalDataFilePathTemp { get; set; }
public static string animalDataFileNameJSON { get; set; }
public static string animalDataFileNameTex { get; set; }
private void Start()
{
InitGameVariables();
}
void InitGameVariables()
{
animalDataFilePathRoot = "/animalData";
animalDataFilePathJSON = "/animalData/json";
animalDataFilePathTex = "/animalData/tex";
animalDataFilePathTemp = "/animalData/tmp";
animalDataFileNameJSON = "/animal.json";
animalDataFileNameTex = "/animalTexture.png";
}
【问题讨论】:
-
好像你没有初始化加载器对象的实例。写类似 var loader = new Loader(); loader.Start();
-
也通过新的 List
初始化文件夹变量