我在初次加载游戏时遇到了创建目录结构的问题。我有一个脚本应该创建一组文件夹,如果它们不存在,但我收到错误: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";
}
答案 0 :(得分:4)
在使用之前初始化folders
变量。
private List<string> folders = new List<string>();
或者在“开始”功能中执行此操作:
private List<string> folders;
private void Start()
{
//Init
folders = new List<string>();
// Create folder List
folders.Add(Application.persistentDataPath + GameManager.animalDataFilePathRoot);
...
...
}
此外,由于您正在使用GameManager
类中的变量,在Start
类的Loader
函数中,因此初始化{{1}中的所有变量是有意义的。 1}} GameManager
函数内的类而不是Awake
函数。
如果您不这样做,Start
和其他类似变量在使用时可能无法初始化。
animalDataFilePathJSON