当前位置:首页 > 动态 > UE4开发入门   > UE4 新手常用C++API
内容详情
UE4 新手常用C++API
来源:      发布时间:2018-05-08 00:38      浏览:3563     字体:    
蓝图调用变量

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "XXX")


开放给编辑器时删选类型

TSubClassOf


蓝图调用函数

UFUNCTION(BlueprintCallable, Category = "XXX")


继承父类
Super::Xxx();  

例:

void BeginDestroy() override;

void AmyActor::BeginDestroy()
{
    Super::BeginDestroy();
    UE_LOG(LogTemp, Warning, TEXT("Game exit!"));
}


蓝图重载C++函数(可以在C++中其他位置调用一个目前没有任何功能的函数(事件),而该函数的具体实现交给蓝图实现)

UFUNCTION(BlueprintImplementableEvent)       

void OnTest(); 


在蓝图中Add Event,找到对应的函数名,创建后即可实现具体逻辑

然后也可以在自己的C++代码中调用该方法

void MyActor::OnPressed()
{
    OnTest();
}


蓝图添加默认的C++实现(C++在调用了SomeFunction()的地方先调用SomeFunction_Implementation的实现,但如果在蓝图中定义了SomeFunction事件(即使后面不连接任何内容),则会忽略C++中SomeFunction_Implementation中的实现,只采用蓝图中的实现)

UFUNCTION(BlueprintNativeEvent, Category = "SomeCategory")

void SomeFunction();

void AMyActor::SomeFunction_Implementation() 

    UE_LOG(LogTemp, Warning, TEXT("Implenetaion in C++")); 

}


判断Actor是蓝图还是C++

Actor->GetClass.IsNative();


判断当前游戏运行模式

GetWorld()->WorldType


加载地图

UGameplayStatics::OpenLevel(GetWorld(), *mapName);


获取屏幕尺寸

const FVector2D ViewportSize = FVector2D(GEngine->GameViewport->Viewport->GetSizeXY());


运行命令

GetWorld()->GetFirstPlayerController()->ConsoleCommand("quit");


打印

GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, FString::Printf(TEXT("%s"),*FString));
#include "Misc/OutputDevice.h"
GLog->Logf(TEXT("%s"), *Filepath);

设置位置
SetActorLocation(FVector(0.0f, 0.0f, 250.0f));


打开EXE

FPlatformProcess::ExecProcess(*QQ, nullptr, nullptr, nullptr, nullptr);

FPlatformProcess::CreateProc(*QQ, nullptr, true, false, false, nullptr, -1, nullptr, nullptr);


MD5加密

FMD5::HashAnsiString(TEXT("someStuff"));


hashi加密

FString HashStringWithSHA1(const FString &InString)
{
    FSHAHash StringHash;
    FSHA1::HashBuffer(TCHAR_TO_ANSI(*InString), InString.Len(), StringHash.Hash);
    return StringHash.ToString();
}


传一个Object蓝图

UPROPERTY(BlueprintReadWrite,EditAnywhere,Category = "XX")
TSubclassOfSkillBlueprintHelperObject;


路径

结构体

USTRUCT(Blueprintable)
struct FAskWayDate
{
    GENERATED_USTRUCT_BODY()
public:
    UPROPERTY(BlueprintReadWrite,EditAnywhere,Category = "XX")
    int OpCode;
    UPROPERTY(BlueprintReadWrite,EditAnywhere,Category = "XX")
    TMap Parameters;
};
FString Str2 = FString::Printf(TEXT("Texture2D'/Game/pan/Frame_%05d.Frame_%05d'"),textName)


查找场景中的Actor

AActor * AMyActor::FindActor(FString Actorname)

{
    AActor* mActor = NULL;
    if (GetWorld())
    {
        for (TActorIteratorIt(GetWorld()); It; ++It)
        {
            AActor* xActor = *It;
            if (xActor->GetName() == Actorname)
            {
                GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("Get it"));
                mActor = xActor;
                break;
            }
        }
        if (!mActor)
        {
            GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("No Get it"));
        }
        return  mActor;
    }
    else
    {
        GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("NO getworld"));
        return nullptr;
    }
}


绑定按键(PS:需要在Pawn或Character里)

void AMyActor::SetupPlayerInputComponent(class UInputComponent* InputComponent)

{
    InputComponent->BindKey(EKeys::Z, IE_Released, this, &AMyActor::OpenURL);
    InputComponent->BindAction("Grow", IE_Released, this, &AMyActor::OpenURL);
    InputComponent->BindAxis("back", this, &AMyActor::OpenURL);
}


返回多个值,引用

void AMyActor::MoreReturn(FString& A, bool& B)

{
}

蓝图显示中文枚举类(VS文件-高级保存选项UTF-8格式)

UENUM(BlueprintType)

enum class EenumChinese :uint8 
{
    E_EN UMETA(DisplayName = "英文"),  
    E_CH UMETA(DisplayName = "中文"),  
};
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "enumChinese")
EenumChinese enumChinese;

双选项枚举类
UENUM(BlueprintType)
enum class EMyEnum : uint8
{
    BranchA,
    BranchB,
};
UFUNCTION(BlueprintCallable, Category = "My|MyActor", Meta = (ExpandEnumAsExecs = "Branches"))
void BranchFun(int32 Input, EMyEnum& Branches);
void AMyActor::BranchFun(int32 Input, EMyEnum& Branches)
{
    if (Input == 1)
    {
        Branches = EMyEnum::BranchA;
    }
    else
    {
        Branches = EMyEnum::BranchB;
    }
}


创建UI   "Media", "MediaAssets"

if (nullptr == MainMenuWidget)    

{        
    UClass* aa = LoadClass( NULL, TEXT( "Blueprint'/Game/UMG/MainMenu.MainMenu_C'" ) );        
    MainMenuWidget = CreateWidget( GetWorld()->GetFirstPlayerController(), aa );    
}    
MainMenuWidget->AddToViewport(); 
//http://blog.csdn.net/zilisen/article/details/77645500


找蓝图Actor

static ConstructorHelpers::FObjectFinderassetObject(TEXT("/Game/Maps/test.test_C")); 

if (assetObject.Succeeded())
{
    TestBlueprint = (UClass*)assetObject.Object->GeneratedClass;
}


找材质

static ConstructorHelpers::FObjectFinderMaterialAsset(TEXT("/Game/Maps/MAT.MAT"));

if (MaterialAsset.Succeeded())
{
    Material = (UMaterial*)MaterialAsset.Object;

}


LOG
UE_LOG(LogTemp, Warning, TEXT("Cannot find xx"));
DEFINE_LOG_CATEGORY(LogMySlate);
UE_LOG(LogMySlate, Warning, TEXT("Found UObject named"));


生成类

TestObjectActor = GWorld->SpawnActor(TestBlueprint);

UWorld* const World = GetWorld();
AActor* GridCube = World->SpawnActor(GridCubeClass2, FVector(0.0f, 90.0f, 50.0f), FRotator(0.0f, 0.0f, 0.0f));


创建Object

UMyObject*NewObj=NewObject();


读取Texture2D

UTexture2D* texture22 = Cast(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(Path)));


获得名字

Actor->GetName() == TEXT("FloatActor_1")


强制转换

PTGameInstance = Cast(World->GetGameInstance());


添加组件

RootComponent = CreateDefaultSubobject(TEXT("Center"));


移动Windows游戏窗口

PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });

if (GEngine && GEngine->GameViewport)
{
    FVector2D WindowPosition = position;
    GEngine->GameViewport->GetWindow()->MoveWindowTo(WindowPosition);
}


设置碰撞类型

SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);


重力

SetEnableGravity(false);


计时器

FTimerHandle CountdownTimerHandle;

GetWorldTimerManager().SetTimer(CountdownTimerHandle, this, &AMytestActor::AdvanceTimer, 1.0f, true);
GWorld->GetTimerManager().UnPauseTimer(mTimer); //唤醒
float elapsed = GWorld->GetTimerManager().GetTimerElapsed(mTimer); //已逝时间
float elapsed = GWorld->GetTimerManager().GetTimerRemaining(mTimer); //剩余时间
bool isActive = GWorld->GetTimerManager().IsTimerActive(mTimer); //激活
bool isPaused = GWorld->GetTimerManager().IsTimerPaused(mTimer); //暂停
bool isExist = GWorld->GetTimerManager().TimerExists(mTimer); //存在
GetWorldTimerManager().ClearTimer(CountdownTimerHandle);//停止计时器


退出游戏

UKismetSystemLibrary::QuitGame(this, nullptr, EQuitPreference::Quit);

GEngine->Exec(GWorld, *FString("Exit"));


获取时间

FDateTime::Now().ToString();


链接URL

FString TheURL = "xxxxxxxx";

FPlatformProcess::LaunchURL(*TheURL, nullptr, nullptr);


获取IP地址

需要在build.cs添加Sockets模块

#include "SocketSubsystem.h"

#include "IPAddress.h"
FString IpAddr("NONE");
bool canBind = false;
TSharedRefLocalIp = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->GetLocalHostAddr(*GLog, canBind);
 if (LocalIp->IsValid())
{
    IpAddr = LocalIp->ToString(false); //(如果想附加端口就写 ture)
}
return IpAddr;


添加标签

MyActor.Tags.AddUnique(TEXT("MyTag"));  


销毁物体

MyActor->Destroy();

MyActor->SetLifeSpan(1);//延迟1S


截图

FString UMyBlueprintFunctionLibrary::TakeScreenShoot(FString picName, bool bUnique /*= true*/)

{
    FString inStr;
    FString Filename;
    FScreenshotRequest::RequestScreenshot(picName + ".png", false, bUnique);
    FString ResultStr = FScreenshotRequest::GetFilename();
    ResultStr = FPaths::GetBaseFilename(ResultStr, true);
    return ResultStr + ".png";

}

void UMyBlueprintFunctionLibrary::Screenshot(const FString InFilename, bool bInShowUI)
{
    FScreenshotRequest SR = FScreenshotRequest();
    FString savelocation = FPaths::ConvertRelativePathToFull(FPaths::GameDir());
    FString filename = savelocation + FString(TEXT("/Saved/Screenshotss/")) + InFilename + FString(TEXT(".png"));
    SR.RequestScreenshot(filename, bInShowUI, false);
}


写入配置文件,有GEditorIni,GEditorProjectIni,GCompatIni,GlightmassIni,GScalabilityIni,GHardwareIni,GInputIni,GGameIni,GGameUserSettingsIni等(查找CoreGlobals.h)

写的数据会写到 YourGame\Saved\Config\Windows\Game.ini 中
const FString WriteSection = "MyCustomSection";
//String
GConfig->SetString(
     *WriteSection,
    TEXT("key1"),
    TEXT("Hello world"),
    GGameIni
);
GConfig->Flush(false, GGameIni);


读取配置

if (!GConfig) 

    return 0;

float ValueReceived ;
GConfig->GetFloat(
    TEXT("MyCustomSection"),
    TEXT("key1"),
    ValueReceived,
    GGameIni
);

return ValueReceived;


UE4中常用的几种方法和节点

1. get/set方法,get表示只是获取到某个物体,可以得到她的所有属性,但是不能进行修改,而set即是可以修改;
2. 判断某个actor或者UI是否显示,isVisibility,在此之前,需要得到需要判断的物体,然后,引出节点isVisibility;
3. 分支:sequence,一个节点可以引发出多个节点,并可以分别同时执行;
4. 创建画布:Creat widget ,单单创建画布是无法在游戏界面中看到的,需要再来一步,add to viewport;
5. 添加到显示屏幕:Add to viewPort,注意里面可以设置Zorder值,Zorder即是画布的层,就比如在Unity里面的UGUI一样,显示也是按照越是新添加的越是显示在最前面,ZOrder值越大,越是最先看到,最先检测、触发,所以再出现有UI重叠的时候可以通过更改Zorder值实现,也可以通过代码动态改变Zorder实现;
6. get all widgets of class  得到所有UI蓝图类,在下面也可以指定某个UI蓝图类的;
7. 在UI中设定某种UI 的显示和隐藏即是visible,Hideen,Collaps等,是通过 set visibility 来实现的;
8. Print String   即是打印字符串,其他的基本数据类型也可以直接将节点连接到该方法,中键自动将数据类型转化成string类型;

9. Build String  就是创建String 或者是组建string,可以将bool,int,float 类型都可以和string类型组成string类型;



创建组件

在UE4中,为Actor创建组件,可使用UObject::CreateDefaultSubobject()模板函数,以下所示:

/* <CreateObjectDemo> * 创建Component对象,要使用CreateDefaultSubobject模板函数 */ 

MyComponent = CreateDefaultSubobject<UMyActorComponent>(TEXT("MyComponent"));


加载资源对象

在UE4中,项目中的所有资源文件,不要看作是文件,而要理解为"静态对象":也就是对象序列化的产物。加载项目资源可使用"UObject::StaticLoadObject()"函数,其中重要的参数为对象的Name,而不是文件路径。

UE底层提供文件读取功能,不管资源文件是存储我独立的.uasset文件,还是存储到.PAK文件中,对上层都不需要关心。

/* <CreateObjectDemo> * 加载模型、贴图等对象,使用StaticLoadObject函数 */ 

UStaticMesh* SM_Vase = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/Game/Assets/StaticMeshes/SM_Vase")) ); 

StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent")); 

StaticMeshComponent->SetStaticMesh(SM_Vase);


创建Actor对象

创建Actor对象,需要使用UWorld::SpawnActor()接口,以下所示:

/* <CreateObjectDemo> * 创建AActor派生类对象不要用NewObject或new,而要用UWorld::SpawnActor() */ 

UWorld* World = GetWorld(); FVector pos(150, 0, 20); 

AMyActor* MyActor = World->SpawnActor<AMyActor>(pos, FRotator::ZeroRotator);


创建UObject对象

如果你有UObject的派生类(非Actor、非ActorComponent),那你可使用NewObject()模板函数来创建其实例对象。

/* <CreateObjectDemo> * 使用NewObject模板函数,来创建UObject派生类对象 */ 

MyObject = NewObject<UMyObject>();





相关阅读:

上一篇: 已经是第一篇了
途联微信号