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



今天我只是想制作自定义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!");
}
}
}

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

最新更新