Unity C# 脚本: 控制台日志计分器
Unity C# 脚本: 控制台日志计分器
该脚本用于监测控制台打印事件并根据其中包含的特定字符串来计分。具体解释如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class jiFen : MonoBehaviour
{
// 操作名称
public UnityEngine.UI.Text point;
private string[] checkStrings = { 'aa', 'b', 'c' }; // 要检查的字符串数组
public int score = 0; // 分数计数器
private List<string> checkedWords = new List<string>(); // 已检查过的字符串列表
private void Start()
{
// 注册事件,监听控制台打印事件
Application.logMessageReceived += OnLogMessageReceived;
}
private void OnLogMessageReceived(string logString, string stackTrace, LogType logType)
{
// 遍历要检查的字符串数组
foreach (string word in checkStrings)
{
// 如果logString包含特定字符串并且该字符串还未被检查过
if (logString.Contains(word) && !checkedWords.Contains(word))
{
score += 5; // 包含特定字符串,加5分
checkedWords.Add(word); // 将该字符串加入已检查过的列表
point.text = score.ToString(); // 更新分数显示
}
}
}
private void OnDestroy()
{
// 取消注册事件,防止内存泄漏
Application.logMessageReceived -= OnLogMessageReceived;
}
}
代码逐行解释:
using System.Collections;: 导入命名空间System.Collections,以便使用集合类。using System.Collections.Generic;: 导入命名空间System.Collections.Generic,以便使用泛型集合类。using UnityEngine;: 导入 Unity 引擎的命名空间。using TMPro;: 导入 TextMeshPro 的命名空间,以便使用 TextMeshPro 相关的类。public class jiFen : MonoBehaviour: 定义了一个名为jiFen的公共类,继承自MonoBehaviour脚本。public UnityEngine.UI.Text point;: 定义了一个公共的UnityEngine.UI.Text类型的变量point,用于显示分数。private string[] checkStrings = { 'aa', 'b', 'c' };: 定义了一个私有的字符串数组checkStrings,用于存储要检查的字符串。public int score = 0;: 定义了一个公共的整数变量score,用于记录分数。private List<string> checkedWords = new List<string>();: 定义了一个私有的字符串列表checkedWords,用于存储已检查过的字符串。private void Start(): 定义了一个私有的方法Start,该方法在脚本启动时执行。Application.logMessageReceived += OnLogMessageReceived;: 注册了一个事件监听器,监听控制台打印事件,并将事件处理方法OnLogMessageReceived作为回调函数。private void OnLogMessageReceived(string logString, string stackTrace, LogType logType): 定义了一个私有的方法OnLogMessageReceived,用于处理控制台打印事件。foreach (string word in checkStrings): 使用foreach循环遍历要检查的字符串数组checkStrings。if (logString.Contains(word) && !checkedWords.Contains(word)): 判断logString是否包含特定字符串word并且该字符串还未被检查过。score += 5;: 如果包含特定字符串,将分数加 5。checkedWords.Add(word);: 将已检查过的字符串加入已检查列表。point.text = score.ToString();: 将分数转换为字符串后更新分数显示。private void OnDestroy(): 定义了一个私有的方法OnDestroy,该方法在脚本被销毁时执行。Application.logMessageReceived -= OnLogMessageReceived;: 取消注册事件监听器,防止内存泄漏。
使用方法:
- 将该脚本添加到场景中的一个游戏对象上。
- 在场景中添加一个
Text对象,并将其设置为jiFen脚本的point属性。 - 运行游戏,并在控制台中打印包含
checkStrings中字符串的信息。 - 每次打印包含
checkStrings中字符串的信息,分数就会增加 5。
注意:
- 该脚本只对控制台打印的信息进行监测,不会监测其他类型的事件。
- 您可以修改
checkStrings数组来指定要监测的字符串。 - 您可以修改
score += 5;语句来更改每次得分增加的值。 - 该脚本使用了
TextMeshPro,如果您没有安装TextMeshPro,则需要将其安装。
原文地址: https://www.cveoy.top/t/topic/plj7 著作权归作者所有。请勿转载和采集!