UE4 C++初探

来源:互联网 发布:控制网络流量软件 编辑:程序博客网 时间:2024/06/06 20:34

UE4 C++ 初探


声明:笔者引擎版本为 Unreal Engine 4.16.1

从打印 Hello World 和打印基本变量开始:

工程的建立和基本代码的编写就不再赘述了,网上有很多,我看的是这个:
http://blog.csdn.net/u011326794/article/details/47706959

可以在新建的AActor中的Tick或者BeginPlay中使用 GEngine 的 AddOnScreenDebugMessage 进行输出,GEngine 是 UEngine 类型的一个全局指针,被声明在 Engine.h 中,源代码如下:

Engine.h

/** Global engine pointer. Can be 0 so don't use without checking. */extern ENGINE_API class UEngine*            GEngine;

在 Engine.cpp 中对 GEngine 进行了初始化:

Engine.cpp

/** * Global engine pointer. Can be 0 so don't use without checking. */ENGINE_API UEngine* GEngine = NULL;
  • UE4 在屏幕上打印文字的函数原型如下:
void UEngine::AddOnScreenDebugMessage(        uint64 Key,        float TimeToDisplay,    // 消息在屏幕上显示的时间        FColor DisplayColor,    // 文字的颜色        const FString & DebugMessage,    // 显示内容        bool bNewrOnTop,        const FVector2D & TextScale)void UEngine::AddOnScreenDebugMessage(        int32 Key,        float TimeToDisplay,    // 消息在屏幕上显示的时间        FColor DisplayColor,    // 文字的颜色        const FString & DebugMessage,    // 显示内容        bool bNewrOnTop,        const FVector2D & TextScale)

官方文档的例子在这里:

void AHelloWorldPrinter::Tick(float DeltaTime)  {      Super::Tick(DeltaTime); //Call parent class Tick      static const FString ScrollingMessage(TEXT("Hello World: "));      if (GEngine)      {          const int32 AlwaysAddKey = -1; // Passing -1 means that we will not try and overwrite an                                          // existing message, just add a new one          GEngine->AddOnScreenDebugMessage(AlwaysAddKey, 0.5f, FColor::Yellow, ScrollingMessage + FString::FromInt(MyNumber));          const int32 MyNumberKey = 0; // Not passing -1 so each time through we will update the existing message instead                                       // of making a new one          GEngine->AddOnScreenDebugMessage(MyNumberKey, 5.f, FColor::Yellow, FString::FromInt(MyNumber));          ++MyNumber; // Increase MyNumber so we can see it change on screen      }  }
  • 贴出一个Demo:
// Called every framevoid AFloatingActor::Tick(float DeltaTime){    Super::Tick(DeltaTime);    FVector NewLocation = GetActorLocation();    if (GEngine)    {        GEngine->AddOnScreenDebugMessage(-1, 8.f, FColor::Blue, TEXT("Hello World !"));        GEngine->AddOnScreenDebugMessage(0, 3.f, FColor::Red, *NewLocation.ToString());    }}
  • 代码说明:

    • Tick 在类创建的时候由编辑器自动创建
    • GetActorLocation() 用来获取 Actor 当前的 Location,返回的是一个 FVector 结构体类型
    • 使用FVector::ToString()将 NewLocation 由 FVector 转为 FString
  • 笔者的代码执行结果如下:
    笔者的代码执行结果

  • 补充:
    • FString 的FString::SanitizeFloat(double Infloat)将 double 类型转为 FString 类型,FString::SanitizeFloat()