93 lines
2.8 KiB
C#
93 lines
2.8 KiB
C#
using UnityEditor;
|
|
using UnityEngine;
|
|
using System;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
[InitializeOnLoad]
|
|
public static class IAPDefineSymbolAdder
|
|
{
|
|
private const string SYMBOL_IAP = "UNITY_IAP";
|
|
private const string SYMBOL_PURCHASING = "UNITY_PURCHASING";
|
|
|
|
static IAPDefineSymbolAdder()
|
|
{
|
|
CheckAndUpdateSymbols();
|
|
}
|
|
|
|
[MenuItem("Tools/IAP/检查并更新宏")]
|
|
public static void CheckAndUpdateSymbols()
|
|
{
|
|
bool iapInstalled = IsIAPInstalled();
|
|
|
|
foreach (BuildTargetGroup group in new[] { BuildTargetGroup.Android, BuildTargetGroup.iOS })
|
|
{
|
|
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group);
|
|
var symbols = defines.Split(';').Where(s => !string.IsNullOrEmpty(s)).ToList();
|
|
|
|
if (iapInstalled)
|
|
{
|
|
// 需要宏但宏不存在 → 添加
|
|
bool changed = false;
|
|
if (!symbols.Contains(SYMBOL_IAP)) { symbols.Add(SYMBOL_IAP); changed = true; }
|
|
if (!symbols.Contains(SYMBOL_PURCHASING)) { symbols.Add(SYMBOL_PURCHASING); changed = true; }
|
|
|
|
if (changed)
|
|
{
|
|
PlayerSettings.SetScriptingDefineSymbolsForGroup(group, string.Join(";", symbols));
|
|
Debug.Log($"[IAP] 检测到 IAP 已安装,已为 {group} 添加宏。");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// 不需要宏但宏存在 → 移除
|
|
bool changed = symbols.Remove(SYMBOL_IAP) || symbols.Remove(SYMBOL_PURCHASING);
|
|
|
|
if (changed)
|
|
{
|
|
PlayerSettings.SetScriptingDefineSymbolsForGroup(group, string.Join(";", symbols));
|
|
Debug.Log($"[IAP] 检测到 IAP 未安装,已为 {group} 移除宏。");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static bool IsIAPInstalled()
|
|
{
|
|
if (TypeExists("UnityEngine.Purchasing.Product"))
|
|
return true;
|
|
|
|
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
|
if (assemblies.Any(a => a.GetName().Name.Contains("UnityEngine.Purchasing")))
|
|
return true;
|
|
|
|
try
|
|
{
|
|
Assembly.Load("UnityEngine.Purchasing");
|
|
return true;
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private static bool TypeExists(string typeName)
|
|
{
|
|
try
|
|
{
|
|
return AppDomain.CurrentDomain.GetAssemblies()
|
|
.SelectMany(assembly =>
|
|
{
|
|
try { return assembly.GetTypes(); }
|
|
catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); }
|
|
})
|
|
.Any(t => t.FullName == typeName);
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|