我在初始加載遊戲時創建目錄結構時遇到問題。我有一個腳本,應該創建一組文件夾,如果它們不存在,但我得到錯誤:NullReferenceException: Object reference not set to an instance of an object Loader.Start() (at Assets/_Scripts/Managers/Loader.cs:22)
我創建了一個我想創建的文件夾的數組,然後使用foreach循環該數組並使用Directory.CreateDirectory(path)
它應該創建該目錄,但它不是。我在這裏做錯了什麼?NullReferenceException在創建文件夾結構時
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.");
}
}
}
變量設置像這樣:
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";
}
好像你沒有初始化Loader-Object的實例。寫一些類似var loader = new Loader(); loader.Start(); – kassi
還通過新列表初始化文件夾變量 –
kassi