Files
CC-Framework.CrashReport/Assets/Runtime/CrashConfig.cs

91 lines
3.2 KiB
C#
Raw Normal View History

2024-04-03 15:13:12 +08:00
using System;
using System.IO;
using UnityEngine;
namespace Runtime
{
[CreateAssetMenu (menuName = "CrashConfig")]
public class CrashConfig : ScriptableObject
{
private const string BuglyGUID = "BuglyGUID";
[SerializeField] private string BuglyAppID;
[SerializeField] private string BuglyChannel;
[SerializeField] private bool HasDebugMode;
[SerializeField] private bool EnableCrashReport;
public event Action<string, string, LogType> LogCallbackEvent;
public bool HasInit => this._hasInit;
private bool _hasInit;
private static CrashConfig _instance;
private static CrashConfig Instance
{
get
{
if (_instance == null)
{
_instance = Resources.Load<CrashConfig> (nameof(CrashConfig));
}
#if UNITY_EDITOR
if (_instance == null)
{
_instance = CreateInstance<CrashConfig> ();
// 自定义资源保存路径
string path = "Assets/Resources";
//如果项目总不包含该路径,创建一个
if (!Directory.Exists (path))
{
Directory.CreateDirectory (path);
}
UnityEditor.AssetDatabase.CreateAsset (_instance, path + $"/{nameof(CrashConfig)}.asset");
UnityEditor.AssetDatabase.Refresh ();
}
#endif
return _instance;
}
}
[RuntimeInitializeOnLoadMethod (RuntimeInitializeLoadType.AfterSceneLoad)]
private static void OnEnableCrashReport ()
{
if (Instance != null && Instance.EnableCrashReport)
{
Instance.InitCrash ();
}
}
private void InitCrash ()
{
if (this._hasInit)
{
return;
}
this._hasInit = true;
var buglyGuid = PlayerPrefs.HasKey (BuglyGUID) ? PlayerPrefs.GetString (BuglyGUID) : Guid.NewGuid ().ToString ();
PlayerPrefs.SetString (BuglyGUID, buglyGuid);
// 开启SDK的日志打印发布版本请务必关闭
if (this.HasDebugMode)
{
BuglyAgent.ConfigDebugMode (true);
}
// 注册日志回调,替换使用 'Application.RegisterLogCallback(Application.LogCallback)'注册日志回调的方式
BuglyAgent.RegisterLogCallback (OnLogCallBack);
BuglyAgent.ConfigDefault (this.BuglyChannel, Application.version , buglyGuid , 0);
BuglyAgent.InitWithAppId (this.BuglyAppID);
// 如果你确认已在对应的iOS工程或Android工程中初始化SDK那么在脚本中只需启动C#异常捕获上报功能即可
BuglyAgent.EnableExceptionHandler ();
}
private void OnLogCallBack (string condition, string stacktrace, LogType type)
{
this.LogCallbackEvent?.Invoke (condition, stacktrace, type);
}
}
}