在以下脚本中,如何在Assets文件夹中获取脚本的路径?
using UnityEngine;
using System.Reflection;
using System.IO;
using UnityEditor;
[InitializeOnLoad]
public class MyWindow : ScriptableObject
{
static string pathToScript;
[MenuItem("Window/My Window")]
static void Open()
{
// Do something with `pathToScript`
}
// This function is NOT called when the object is loaded.
protected void OnEnable()
{
var script = MonoScript.FromScriptableObject( this );
pathToScript = AssetDatabase.GetAssetPath( script );
}
}
问题是OnEnabled
它没有被调用,似乎获取脚本路径的唯一方法是通过AssetDatabase.GetAssetPath
,这需要一个实例。
Unity中的版本是5.5.0b3。
答案 0 :(得分:1)
要在继承OnEnable()
时调用ScriptableObject
函数,您必须从CreateInstance()
类调用ScriptableObject
函数。
[InitializeOnLoad]
public class MyWindow : ScriptableObject
{
static string pathToScript;
static MyWindow windowInstance;
[MenuItem("Window/My Window")]
static void Open()
{
Debug.Log("Open:" + pathToScript);
//Do something with `pathToScript`
if (windowInstance == null)
windowInstance = ScriptableObject.CreateInstance<MyWindow>();
}
protected void OnEnable()
{
Debug.Log("Enabled!");
var script = MonoScript.FromScriptableObject(this);
pathToScript = AssetDatabase.GetAssetPath(script);
}
}
使用ScriptableObject.CreateInstance
的另一种方法是从另一个脚本调用它。
[InitializeOnLoad]
public class MyWindow : ScriptableObject
{
static string pathToScript;
[MenuItem("Window/My Window")]
static void Open()
{
Debug.Log("Open:" + pathToScript);
//Do something with `pathToScript`
}
protected void OnEnable()
{
Debug.Log("Enabled!");
var script = MonoScript.FromScriptableObject(this);
pathToScript = AssetDatabase.GetAssetPath(script);
}
}
<强>测试强>:
public class Test : MonoBehaviour
{
public MyWindow myWindow;
public void OnEnable()
{
if (myWindow == null)
myWindow = Object.FindObjectOfType<MyWindow>();
if (myWindow == null)
myWindow = ScriptableObject.CreateInstance<MyWindow>();
}
}