-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScriptableObjectCreator.cs
113 lines (88 loc) · 2.54 KB
/
ScriptableObjectCreator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#if UNITY_EDITOR
using System;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEditor;
using System.IO;
namespace Utilities {
public abstract class ScriptableObjectCreator<T> : SerializedScriptableObject where T : ScriptableObject, new() {
protected abstract string SavePath { get; }
protected abstract void AdditionalInitialization(T obj);
protected abstract bool AdditionalValidation();
protected abstract void AdditionalReset();
[ShowInInspector, PropertyOrder(0)]
public string Name { get; set; }
T _item;
[ShowInInspector, PropertyOrder(1), InlineEditor, HideReferenceObjectPicker]
public T item {
get => _item;
set { }
}
void OnEnable() {
AdditionalReset();
_item = CreateInstance<T>();
_item.name = "New";
Name = "";
}
[Button, PropertyOrder(99)]
protected void CreateAsset() {
if (!AdditionalValidation()) { return; }
string path = "";
if (!SavePath.StartsWith("Assets/")) { path += "Assets/"; }
path += SavePath;
if (!SavePath.EndsWith("/")) { path += "/"; }
path += Name;
path += ".asset";
Debug.Log($"Create {Name} at: {path}...");
if (!IsInputValid(path)) { return; }
var obj = item;
AdditionalInitialization(obj);
AssetDatabase.CreateAsset(obj, path);
EditorUtility.SetDirty(obj);
Debug.Log($"{Name} successfully created as {path}");
LastCreatedAsset = obj;
OnEnable();
}
[SerializeField, HideInInspector] T LastCreatedAsset;
[Button, PropertyOrder(100), PropertySpace]
void GoToLastCreatedAsset() {
if (LastCreatedAsset != null) {
ProjectWindowUtil.ShowCreatedAsset(LastCreatedAsset);
}
else { Debug.Log("Last created asset cannot be found."); }
}
#region Path Validation Logic
bool IsInputValid(string path) {
if (!IsStringValid(SavePath, Path.GetInvalidPathChars())) {
Debug.Log("Wrong Save Path");
return false;
}
if (!IsStringValid(Name, Path.GetInvalidFileNameChars())) {
Debug.Log("Wrong Name");
return false;
}
if (!AssetDatabase.IsValidFolder(SavePath)) {
Debug.Log("Wrong Folder");
return false;
}
if (UnityEngine.Windows.File.Exists(path)) {
Debug.Log("File already exists");
return false;
}
return true;
}
bool IsStringValid(string s, char[] invalidCharacters) {
if (String.IsNullOrWhiteSpace(s)) {return false; }
foreach (var character in invalidCharacters) {
if (s.Contains(character.ToString())) {
Debug.Log(character);
return false;
}
}
if (s.Contains(".")) { return false; }
return true;
}
#endregion
}
}
#endif