Unity - 自定义变量设置解决方案

Unity - Custom variables setting solution

今天我只是想制作自定义 Unity 脚本检查器,但我遇到了一个问题:我无法获取文件内容。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

[CustomEditor(typeof(MonoScript))]
public class SimpleEditCore : Editor {

    public string text;
    public string path;

    public SimpleEditCore(){
        text = new StreamReader (path).ReadToEnd ();
    }

    public override void OnInspectorGUI()
    {
        path = AssetDatabase.GetAssetPath (target);

        // code using text and path
    }
}

现在的问题是:我需要将文本区域文本设置为文件(脚本)文本,但要使其可编辑,我需要使用 OnInspectorGUI() 以外的其他功能,但是当我将代码放入 public SimpleEditCore(),我只是无法获取文件的路径,因为文件的路径是目标,而这个目标只在OnInspectorGUI()中定义。如何解决?

文档显示了一个名为 OnEnable 的方法,可用于在加载对象时获取序列化值

https://docs.unity3d.com/ScriptReference/Editor.html

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

[CustomEditor(typeof(MonoScript))]
public class SimpleEditCore : Editor {

public string text;
public string path;

void OnEnable()
{
     text = serializedObject.FindProperty ("text");         
}

public override void OnInspectorGUI()
{
    path = AssetDatabase.GetAssetPath (target);

    EditorGUILayout.LabelField ("Location: ", path.ToString ());

    text = EditorGUILayout.TextArea (text);

    if (GUILayout.Button ("Save!")) {
        StreamWriter writer = new StreamWriter(path, false);
        writer.Write (text);
        writer.Close ();
        Debug.Log ("[SimpleEdit] Yep!");
    }
}
}

但总体而言,我认为您缺少此对象的价值。它应该提供一个接口来序列化数据而无需知道文件路径。您应该能够只存储数据元素并在不知道文件路径的情况下对其进行序列化。