- Home /
Finding path(Directory) of Script from class
I know you can find the path of the script file if you have an instance: AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(instance));
However it seems odd to me that you need to have an instance of the object to get the path of the script. I need this in a static method so I don't have any reference to an object and it seems odd to just create a new instance for just finding the path.
Is there a way to do it with something like typeof(ClassName)?
Answer by DaCookie · May 08, 2020 at 12:10 AM
Hi! This is an old thread, but for anyone who gets on this page, here is a solution.
Since you need an instance of a ScriptableObject
, you can create an empty one through code without saving any asset, gets its source script path, and then destroy it.
To test that, create a script TestScriptableObject.cs
anywhere in your project, and copy the following code:
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[CreateAssetMenu]
public class TestScriptableObject : ScriptableObject
{
#if UNITY_EDITOR
[MenuItem("Tests/Log TestScriptableObject script path")]
public static void LogTestScriptableObjectPath()
{
// Create the asset instance
TestScriptableObject tmpInstance = ScriptableObject.CreateInstance<TestScriptableObject>();
// Get the script asset used by the object
MonoScript sourceScriptAsset = MonoScript.FromScriptableObject(tmpInstance);
// Log the script path, using AssetDatabase.GetAssetPath() as you said
Debug.Log("Path to TestScriptableObject script: " + AssetDatabase.GetAssetPath(sourceScriptAsset));
// Use DestroyImmediate() to destroy the created asset in edit mode
DestroyImmediate(tmpInstance);
}
#endif
}
If you click on the new menu Tests > Log TestScriptableObject script path, you will see the path to the source script path in the console window.
I hope I helped :)
This doesn't work if TestScriptableObject is a static class, though.
Your answer
Follow this Question
Related Questions
DirectoryNotFoundException with full existing path... ? How can this be? I need an answer ASAP 1 Answer
Possible to move directory without reimporting assets? 3 Answers
Multiple Editor and Plugins Directory 3 Answers
Unity double save/back-up 1 Answer
Debug.Log(files in a directory) problem 0 Answers