创建文件夹结构时出现NullReferenceException

时间:2017-07-31 05:22:27

标签: c# unity3d io directory

我在初次加载游戏时遇到了创建目录结构的问题。我有一个脚本应该创建一组文件夹,如果它们不存在,但我收到错误: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";
    }

1 个答案:

答案 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