fix: if not configured as a preloaded asset, the project settings asset will be regenerated

close #342
main
mob-sakai 2024-11-21 01:39:16 +09:00
parent 2a66393cb0
commit 5f479902aa
1 changed files with 31 additions and 10 deletions

View File

@ -1,9 +1,9 @@
using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
using Object = UnityEngine.Object;
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
@ -14,6 +14,14 @@ namespace Coffee.UIParticleInternal
public abstract class PreloadedProjectSettings : ScriptableObject
#if UNITY_EDITOR
{
private class Postprocessor : AssetPostprocessor
{
private static void OnPostprocessAllAssets(string[] _, string[] __, string[] ___, string[] ____)
{
Initialize();
}
}
private class PreprocessBuildWithReport : IPreprocessBuildWithReport
{
int IOrderedCallback.callbackOrder => 0;
@ -24,32 +32,32 @@ namespace Coffee.UIParticleInternal
}
}
[InitializeOnLoadMethod]
[InitializeOnEnterPlayMode]
private static void Initialize()
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
foreach (var t in TypeCache.GetTypesDerivedFrom(typeof(PreloadedProjectSettings<>)))
{
var defaultSettings = GetDefaultSettings(t);
if (!defaultSettings)
{
// When create a new instance, automatically set it as default settings.
defaultSettings = t.GetProperty("instance", flags)
?.GetValue(null, null) as PreloadedProjectSettings;
defaultSettings = CreateInstance(t) as PreloadedProjectSettings;
SetDefaultSettings(defaultSettings);
}
else if (GetPreloadedSettings(t).Length != 1)
{
SetDefaultSettings(defaultSettings);
}
}
EditorApplication.QueuePlayerLoopUpdate();
if (defaultSettings)
{
defaultSettings.OnInitialize();
}
}
}
protected static string GetDefaultName(Type type, bool nicify)
{
var typeName = type.Name.Replace("ProjectSettings", "");
var typeName = type.Name;
return nicify
? ObjectNames.NicifyVariableName(typeName)
: typeName;
@ -74,6 +82,7 @@ namespace Coffee.UIParticleInternal
protected static void SetDefaultSettings(PreloadedProjectSettings asset)
{
if (!asset) return;
var type = asset.GetType();
if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(asset)))
{
@ -84,7 +93,11 @@ namespace Coffee.UIParticleInternal
var assetPath = $"Assets/ProjectSettings/{GetDefaultName(type, false)}.asset";
assetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath);
AssetDatabase.CreateAsset(asset, assetPath);
if (!File.Exists(assetPath))
{
AssetDatabase.CreateAsset(asset, assetPath);
asset.OnCreateAsset();
}
}
var preloadedAssets = PlayerSettings.GetPreloadedAssets();
@ -98,6 +111,14 @@ namespace Coffee.UIParticleInternal
AssetDatabase.Refresh();
}
protected virtual void OnCreateAsset()
{
}
protected virtual void OnInitialize()
{
}
}
#else
{