5

Sorry for my English (Google Translate). The following is a snippet of code that creates an asset (ScriptableObject) in the selected directory (Assets/Resources/TestObject.asset):

[MenuItem("Assets/Create/Test Object")]
private static void CreateTestObject()
{
    var testObject = ScriptableObject.CreateInstance<TestObject>();
    AssetDatabase.CreateAsset(testObject, "Assets/Resources/TestObject.asset");
    AssetDatabase.SaveAssets();
}

How can I get the path to the directory I'm in? In order to don´t hardcode the path manually, but to save this GameObject in the same folder where I call the method.


For example:

1) I call the method from Assets/TestFolder/TestFolder2.

2) And in this same directory it creates an asset (TestObject). And does not create in Assets/Resources.

To sum up, I need to get the path to the directory in which I called the method through the menu (Assets/Create/Test Object).


Additionally: Can I immediately rename the GameObject after creating it? As with other objects (scripts, folders, etc.).

Thanks in advance for your answers!


Example (screenshot): How do I get the path that is highlighted in red. I'll call the method through the menu (Create/Test Object). In the directory I have chosen (Assets/TestFolder/TestFolder2). And the asset is created there. And not in Assets/Resources. I need a method that will return a string to me: Assets/TestFolder/TestFolder2.

marsep
  • 51
  • 1
  • 4

2 Answers2

3

While HedgehogNSK's answer is certainly correct, you may find yourself in a situation where you want to create an asset in the current folder outside the context of a Create menu (for instance, via a custom EditorWindow). In this case, you can use the same method the editor does internally, ProjectWindowUtil.CreateAsset(Object asset, string path). This will both create an asset from the provided object and give the user a chance to rename it, just like the default entries under Create do. Example:

private static void CreateTestObject()
{
    var testObject = ScriptableObject.CreateInstance<TestObject>();
    // Do some custom initialization logic for testObject
    ProjectWindowUtil.CreateAsset(testObject, "TestObject.asset");
}

The ProjectWindowUtil class is not documented, but is public and can be readily found in the Unity Reference Source here. CreateAsset in particular has existed for several years now, so it is probably safe to assume it's not going anywhere.

AlphaModder
  • 3,266
  • 2
  • 28
  • 44
0

Use [CreateAssetMenu] for creating ScriptableObject, instead of [MenuItem].
When you use CreateAssetMenu attribute it adds option to Assets -> Create which creates object in current folder.

[CreateAssetMenu(menuName = "MyApp/TestClass")]
public class TestClass: ScriptableObject
{
}
colinD
  • 1,641
  • 1
  • 20
  • 22
  • 1
    Sometimes that is not an option, for example if creation requires additional steps before the file is created. –  Jun 26 '22 at 17:35