Created
October 2, 2023 06:47
-
-
Save aprius/8681c156a660f3fbf2ec87d6b65be35e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Linq; | |
#if UNITY_EDITOR | |
using UnityEditor; | |
#endif | |
using UnityEngine; | |
public class FooConfig : ScriptableObject | |
{ | |
private static FooConfig _instance; | |
public static FooConfig Instance | |
{ | |
get | |
{ | |
#if UNITY_EDITOR | |
if (_instance == null) | |
{ | |
var asset = PlayerSettings.GetPreloadedAssets().OfType<FooConfig>().FirstOrDefault(); | |
_instance = asset != null ? asset : CreateDefault(); | |
} | |
return _instance; | |
#else | |
if (_instance == null) | |
{ | |
_instance = CreateInstance<FooConfig>(); | |
} | |
return _instance; | |
#endif | |
} | |
private set => _instance = value; | |
} | |
private void OnEnable() | |
{ | |
_instance = this; | |
} | |
#if UNITY_EDITOR | |
[MenuItem("Assets/Create/FooConfig")] | |
private static void Create() | |
{ | |
var asset = PlayerSettings.GetPreloadedAssets().OfType<FooConfig>().FirstOrDefault(); | |
if (asset != null) | |
{ | |
throw new InvalidOperationException($"{nameof(FooConfig)} already exists in preloaded assets"); | |
} | |
var assetPath = EditorUtility.SaveFilePanelInProject($"Save {nameof(FooConfig)}", nameof(FooConfig), | |
"asset", "", "Assets"); | |
if (string.IsNullOrEmpty(assetPath)) | |
{ | |
return; | |
} | |
var folderPath = Path.GetDirectoryName(assetPath); | |
if (!string.IsNullOrEmpty(folderPath) && !Directory.Exists(folderPath)) | |
{ | |
Directory.CreateDirectory(folderPath); | |
} | |
var instance = CreateInstance<FooConfig>(); | |
AssetDatabase.CreateAsset(instance, assetPath); | |
var preloadedAssets = PlayerSettings.GetPreloadedAssets().ToList(); | |
preloadedAssets.Add(instance); | |
PlayerSettings.SetPreloadedAssets(preloadedAssets.ToArray()); | |
AssetDatabase.SaveAssets(); | |
} | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment