I have a C++ DLL and I would like to Log to the Unity Console when in Play mode.
Is the a way to display text to the Unity console from C++ ? Can I just use ‘std::cout’ ?
This is not working for me. Thanks.
I don’t think so.
I just pass strings back from my native C functions and then output it via Unity. You could just accumulate all the strings in C++ side and then have another function that returns those strings to Unity.
Here’s a solution with a callback function:
Interesting! Last time I checked you had to wait until the next frame to send stuff back… what you posted looks like it might happen immediately. Cool.
I assume its a direct callback to this C# class and a static class method (in memory) and therefore its frame independent, but runs on the main thread so I would use it sparingly or only in a developer build.
- Thanks. I will try both of these suggestions.
This works wonders! Thanks
Try this github.
You need to include Native api from PluginAPI (e.g. %UNITY_LOCATION%\Editor\Data\PluginAPI)
In your cpp:
static IUnityLog* mLogger;
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API SendDataFromUnityToLog(float t)
{
// Call it using the define below
string content = "Native log: " + to_string(t);
const char* c_content = content.c_str();
UNITY_LOG(mLogger, c_content);
UNITY_LOG_WARNING(mLogger, c_content);
UNITY_LOG_ERROR(mLogger, c_content);
}
// This will be called when this plugin is loaded
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces * pInterfaces)
{
// Store this IUnityLog
mLogger = pInterfaces->Get<IUnityLog>();
UNITY_LOG(mLogger, "Native Plugin load");
}
extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload()
{
UNITY_LOG(mLogger, "Native Plugin unload");
mLogger = nullptr;
}
In your cs file
[DllImport("NativePlugin")]
private static extern void SendDataFromUnityToLog(float _);
private void Start()
{
UnityEngine.Random.InitState(System.DateTime.Now.Second);
float randNum = UnityEngine.Random.value;
Debug.Log("Unity Log: " + randNum.ToString());
// Trigger the UnityPluginLoad(c++) once you call this function
SendDataFromUnityToLog(randNum);
}