Version: 6000.3
语言: 中文
用于分析的本机插件 API
代码优化

用于日志记录的本机插件 API

从本机写入 Unity 日志插件在 Unity 外部创建的一组代码,用于在 Unity 中创建功能。可以在 Unity 中使用两种插件:托管插件(使用 Visual Studio 等工具创建的托管 .NET 程序集)和本机插件(特定于平台的本机代码库)。详细信息
请参阅术语表
使用IUnityLog接口。用于日志记录的低级本机 API 在IUnityLog.h头文件,位于 PluginAPI 文件夹中。

该文件包含单个Log函数具有以下变形:

void(UNITY_INTERFACE_API * Log)(UnityLogType type, const char* message, const char *fileName, const int fileLine);

您可以直接调用此函数,如下所示:

s_UnityLog->Log(kUnityLogTypeLog, "Here is a regular log", __FILE__, __LINE__);

但是,为方便起见,本机日志记录 API 定义了以下宏,这些宏包装了对Log功能:

描述
UNITY_LOG(PTR_, MSG_) 使用作为指针传递的日志接口 (PTR_) 写入提供的 char*MSG_作为常规日志消息。相当于托管 API Debug.Log
UNITY_LOG_WARNING(PTR_, MSG_) 使用作为指针传递的日志接口 (PTR_) 写入提供的 char*MSG_作为警告级日志消息。等效于托管 API Debug.LogWarning
UNITY_LOG_ERROR(PTR_, MSG_) 使用作为指针传递的日志接口 (PTR_) 写入提供的 char*MSG_作为错误级别的日志消息。等效于托管 API Debug.LogError

以下代码示例实现了IUnityLogC++接口,并使用这些预定义的宏来编写不同级别的日志输出:

#include "IUnityLog.h"

static IUnityLog* s_UnityLog = NULL;

// Additional macros to include file and line number from the native code
#define UNITY_LOG_STRINGIZE_DETAIL(x) #x
#define UNITY_LOG_STRINGIZE(x) UNITY_LOG_STRINGIZE_DETAIL(x)
#define COMPOSE(MESSAGE) "[" __FILE__ ":" UNITY_LOG_STRINGIZE(__LINE__) "] " MESSAGE
#define NATIVE_LOG(PTR, MESSAGE) UNITY_LOG(PTR, COMPOSE(MESSAGE))
#define NATIVE_WARNING(PTR, MESSAGE) UNITY_LOG_WARNING(PTR, COMPOSE(MESSAGE))
#define NATIVE_ERROR(PTR, MESSAGE) UNITY_LOG_ERROR(PTR, COMPOSE(MESSAGE))

// Unity plugin load event
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces * unityInterfacesPtr)
{
    s_UnityLog = unityInterfacesPtr->Get<IUnityLog>();
}

// Unity plugin unload event
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
{
    s_UnityLog = nullptr;
}

extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API GenerateLog()
{
    // Output different log level messages to the Unity console
    UNITY_LOG(s_UnityLog, "Regular log message");
    UNITY_LOG_WARNING(s_UnityLog, "Warning log message");
    UNITY_LOG_ERROR(s_UnityLog, "Error log message");

    // Wrap log functions to provide native file and line number in output
    NATIVE_LOG(s_UnityLog, "Regular log with native file name and line number");
    NATIVE_WARNING(s_UnityLog, "Warning log with native file name and line number");
    NATIVE_ERROR(s_UnityLog, "Error log with native file name and line number");
}

注意:用于在消息中嵌入本机文件和行号的其他宏是已知问题的解决方法,即 Unity 无法在Log函数通过UNITY_LOG和等价物。

其他资源

用于分析的本机插件 API
代码优化