-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconsole.unity.ts
79 lines (75 loc) · 2.52 KB
/
console.unity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { UnityEngine, UnityEditor } from 'csharp';
import { $typeof } from 'puerts';
enum LogType {
Error = 0,
Assert = 1,
Warning = 2,
Log = 3,
Exception = 4
}
const scriptResources = new Map<string, UnityEngine.Object>();
const emptyResources = new UnityEngine.Object();
const isUnityEditor = UnityEngine.Application.isEditor;
function print(type: LogType, showStack : boolean, ...args) {
let message = '';
for (let i = 0; i < args.length; i++) {
const element = args[i];
if (typeof element === 'object' && console.LOG_OBJECT_TO_JSON) {
message += JSON.stringify(element);
} else {
message += element;
}
if (i < args.length - 1) {
message += ' ';
}
}
let unityLogTarget: UnityEngine.Object = null;
if (showStack || UnityEngine.Application.isEditor) {
var stacks = new Error().stack.split('\n');
for (let i = 3; i < stacks.length; i++) {
let line = stacks[i];
message += '\n';
if (isUnityEditor) {
const matches = line.match(/at\s.*?\s\((.*?)\:(\d+)/);
if (matches && matches.length >= 3) {
let file = matches[1].replace(/\\/g, '/');
file = file.replace(/.*\/Assets\//, 'Assets/');
const lineNumber = matches[2];
line = line.replace(/\s\(/, ` (<a href="${file}" line="${lineNumber}">`);
line = line.replace(/\)$/, ' </a>)');
if (!unityLogTarget) {
if (!scriptResources.has(file)) {
scriptResources.set(file, UnityEditor.AssetDatabase.LoadAssetAtPath(file, $typeof(UnityEngine.Object)));
}
unityLogTarget = scriptResources.get(file);
}
}
}
message += line;
}
}
message = message.replace(/{/gm, '{{');
message = message.replace(/}/gm, '}}');
UnityEngine.Debug.LogFormat(type, UnityEngine.LogOption.NoStacktrace, unityLogTarget || emptyResources, message);
}
const ConsoleObject = {
log: (...args) => print(LogType.Log, false, ...args),
info: (...args) => print(LogType.Log, true, ...args),
trace: (...args) => print(LogType.Log, true, ...args),
warn: (...args) => print(LogType.Warning, true, ...args),
error: (...args) => print(LogType.Error, true, ...args),
LOG_OBJECT_TO_JSON: false,
};
if (typeof(console) === 'undefined') {
Object.defineProperty(globalThis, 'console', {
value: ConsoleObject,
enumerable: true,
configurable: true,
writable: false
});
} else {
let globalConsole = (globalThis as unknown)['console'];
for (const key in ConsoleObject) {
Object.defineProperty(globalConsole, key, { value: ConsoleObject[key], enumerable: true, configurable: true, writable: typeof(ConsoleObject[key]) !== 'function' });
}
}