I’m working on a seemingly convoluted editor utility where I find myself needing to convert a whole script into a string in order to search for a certain term using string.Contains.
I’m looking to do something like this : (C#-Like Pseudo-code incoming)
string entireScriptToString = string.GetContents("MyClass.cs");
or
GameObject.Find("MyClass").GetComponent<MyOtherClass>().Contents.ToString();
Any ideas? I have writing a script from code down, but reading it is a bit more difficult it seems.
A script inside the Unity editor is represented by a MonoScript instance. The MonoScript class itself is derived from TextAsset and actually represents the source code of your script. You can obtain a specific MonoScript instance by using MonoScript.FromMonoBehaviour for MonoBehaviours and MonoScript.FromScriptableObject for ScriptableObjects.
You need to have an instance of the MonoBehaviour / ScriptableObject for those methods. Unfortunately there’s no overload / version that takes a System.Type but it looks like that’s not what you want.
So if you have an instance of a MonoBehaviour, just pass it to MonoScript.FromMonoBehaviour to get the MonoScript instance.
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
public static class MonoBehaviourEditorExtension
{
public static string GetScriptContent(this MonoBehaviour aInstance)
{
var script = MonoScript.FromMonoBehaviour(aInstance);
if (script != null)
return script.text;
return "";
}
}
#endif
That extension method allows you to directly get the string content of the script file that contains the class. Keep in mind that MonoBehaviours can be inside an already compiled assembly in which case there is no source file.