Skip to content

Instantly share code, notes, and snippets.

@nae3na
Created July 5, 2021 08:53
Show Gist options
  • Save nae3na/d1c372fa40f046f44dd15fd3fb93e140 to your computer and use it in GitHub Desktop.
Save nae3na/d1c372fa40f046f44dd15fd3fb93e140 to your computer and use it in GitHub Desktop.
Debug.Logを画面に表示するサンプル
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class PLogView : MonoBehaviour {
/// <summary>
/// ログの内容
/// </summary>
public class LogData {
// メッセージ
public string condition;
// スタックトレース
public string stacktrace;
// ログの種類
public LogType type;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="condition">メッセージ</param>
/// <param name="stacktrace">スタックトレース</param>
/// <param name="type">ログの種類</param>
public LogData( string condition, string stacktrace, LogType type ) {
this.condition = condition;
this.stacktrace = stacktrace;
this.type = type;
}
}
// ログリスト
private List< LogData > m_LogEntries = new List< LogData >( );
// コールバックイベントを登録する
void Start( ) {
Application.logMessageReceived += this.LogReceive;
}
// コールバックイベントを破棄する
void OnDestroy( ) {
Application.logMessageReceived -= this.LogReceive;
}
void Update( ) {
if ( Input.GetKeyDown( KeyCode.I ) ) UnityEngine.Debug.Log( "Logだよ" );
if ( Input.GetKeyDown( KeyCode.W ) ) UnityEngine.Debug.LogWarning( "Warningだよ" );
if ( Input.GetKeyDown( KeyCode.E ) ) UnityEngine.Debug.LogError( "Errorだよ" );
}
void OnGUI( ) {
GUIStyle logStyle = new GUIStyle( GUI.skin.box );
logStyle.alignment = TextAnchor.UpperLeft;
logStyle.richText = true;
logStyle.wordWrap = true;
// ログの描画
for ( int i = m_LogEntries.Count - 1; i >= 0; --i ) {
string text = string.Format( "{0}\n{1}", m_LogEntries[ i ].condition, m_LogEntries[ i ].stacktrace );
GUILayout.Box( text, logStyle );
}
}
/// <summary>
/// ログが出力されるたびに呼ばれる
/// </summary>
/// <param name="condition">メッセージ</param>
/// <param name="stackTrace">スタックトレース</param>
/// <param name="type">ログの種類</param>
public void LogReceive( string condition, string stackTrace, LogType type ) {
// スタックトレースを置き換え
stackTrace = stackTrace.Trim( );
if ( string.IsNullOrEmpty( stackTrace ) ) {
stackTrace = new StackTrace( true ).ToString( );
}
LogData log = new LogData( condition.Trim( ), stackTrace, type );
// ログを追加
m_LogEntries.Add( log );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment