为unity 3d编辑器编写代码并加载json数据文件,但在Unity编辑器中出现错误

时间:2018-06-22 19:18:24

标签: unity3d-editor

public class GameDataEditor : EditorWindow{      
public GameData gameData;
private string gameDataProjectFilePath = "/StreamingAssets/data.json";

//[MenuItem("Window/Game Data Editor")]
static void Init()
{
    EditorWindow.GetWindow(typeof(GameDataEditor)).Show();
}

void OnGUI()
{
    if (gameData != null)
    {
        GameDataEditor obj = ScriptableObject.CreateInstance<GameDataEditor>();

        SerializedObject serializedObject = new SerializedObject(obj);
        SerializedProperty serializedProperty = serializedObject.FindProperty("gameData");
        Debug.Log("myInt " + gameData.allRoundData.Length);
        EditorGUILayout.PropertyField(serializedProperty, true);

        serializedObject.ApplyModifiedProperties();

        if(GUILayout.Button("Save data"))
        {
            SaveGameData();
        }
    }

    if (GUILayout.Button("Load Data"))
    {
        LoadGameData();
    }
}

private void LoadGameData()
{
    string filePath = Application.dataPath + gameDataProjectFilePath;
    if (File.Exists(filePath))
    {
        string dataAsJson = File.ReadAllText(filePath);
        gameData = JsonUtility.FromJson<GameData>(dataAsJson);
        Debug.Log("File Exists " + gameData.allRoundData[0].name);
    }
    else
    {
        gameData = new GameData();
        Debug.Log("File not found");
    }
}

private void SaveGameData()
{
    string dataAsJson = JsonUtility.ToJson(gameData);
    string filePath = Application.dataPath + gameDataProjectFilePath;
    File.WriteAllText(filePath,dataAsJson);
}

}

遇到错误。 NullReferenceException:对象引用未设置为对象的实例UnityEditor.PropertyHandler.OnGUILayout(UnityEditor.SerializedProperty属性,UnityEngine.GUIContent标签,布尔值includeChildren,

EditorGUILayout.PropertyField(serializedProperty, true);

0 个答案:

没有答案