0

Today I am just trying to make custom Unity script inspector, but I am facing a problem: I can´t get content of file.

This is my code:

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
    }
}

And now the problem: I need to set textarea text ot text of file (script), but to make it editable I need to use other function than OnInspectorGUI(), but when I put code into public SimpleEditCore(), I just can´t get the path of file, because the path of the file is target and this target is only defined in OnInspectorGUI(). How to solve that?

0

1 Answer 1

0

The documentation shows a method called OnEnable that can be used to get the serialized values when the object is loaded

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!");
    }
}
}

However overall I think you are missing the value of this object. It's supposed to give an interface to serialize data without needing to know the file path. You should be able to just store data elements and serialize them without knowing the file path.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.