本文主要是介绍UE4C++笔记(_杰森大师),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
UE4 c++ cast的用法
.CPP中先获取要cast的类的.h头文件
在获取Kismet/GameplayStatics.h
#include"Public/Character/GameCharacter.h"//自己想cast的类
#include"Kismet/GameplayStatics.h"AGameCharacter*MyCharacter=Cast<AGameCharacter>(UGameplayStatics::GetPlayerPawn(this,0));
UE4 switch 整数的用法
在.H里面创建一个整数
int32 Number;.cpp
switch(Number)
{
default:
break;
case 1:
Number=2;//你想做的事情
break;
case 2:
Number=1;//你想做的事情
break;
}
UE4获取Character类中默认的SkeletalMesh
GetMesh()->
UE4使用动画蒙太奇
先创建一个animmontage
.h
UPROPERTY(EditDefaultsOnly, Category = "AnimMontage")class UAnimMontage*AttackAnim1;
.cpp
#include "Animation/AnimMontage.h"
在函数中写
PlayAnimMontage(AttackAnim1);
UE4文件使用
文件操作类:FFileHelper
可用于创建txtFFileHelper::SaveStringToFile(const FString& Content, const TCHAR* Filename, EEncodingOptions EncodingOptions = EEncodingOptions::AutoDetect, IFileManager* FileManager = &IFileManager::Get(), uint32 WriteFlags = 0 );
在自己定义的类中定义
FFileHelper::SaveStringToFile("\r\n"+Content, *Filename);
文件操作类:IPlatformFile
IPlatformFile& fileManager=FPlatformFileManager::Get().GetPlatformFile();//对IPlatformfile进行实例化后面进行调用
fileManager.CreateDirectoryTree(const TCHAR*Directory);
fileManager.DeleteFile();
路径操作类: FPaths
FPaths::RootDir();//返回根目录路径
FPaths::ProjectDir();//返回项目所在文件夹路径,注意:4.18版本为 GameDir();已经无法在新版中使用
FPaths::ProjectConfigDir();//返回项目配置文件夹路径FPaths::RemoveDuplicateSlashes(FString& InPath);//删除InPath中重复的斜杠
FPaths::ConvertRelativePathToFull(const FString& InPath);//将相对路径转换为绝对路径并返回
Overlap(C++)
.H
UPPROPERTY()
class UBoxComponent*CapusleComp;
UFUNCTION()
void OnOverlapBegin(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex,bool bFromSweep, const FHitResult & SweepResult);
UFUNCTION()
void OnOverlapEnd(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
.CPP
AActor::AActor()
{
CapusleComp=CreateDefaultSubobject<UBoxComponent>(TEXT("CapusuleComp"));
CapusleComp->SetupAttachment(Rootment);
CapusleComp->SetBoxExtent(FVector(20.0f,20.0f,20.0f));
CapusleComp->bDynamicObstacle=true;
CapusleComp->bGenerateOverlapEvents=true;
CapusleComp->SetCollisionResponseToAllChannels(ECR_Overlap);FScriptDelegate DelegateBegin;
DelegateBegin.BindUFunction(this,"OnOverlapBegin");
CaapusleComp->OnComponentBeginOverlap.Add(DelegateBegin);
}void AActor:: OnOverlapBegin(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex,bool bFromSweep, const FHitResult & SweepResult)
{
GEngine->AddOnScreenDebugMessage(-1,2.0f,FColor::Yellow,FString("ss"));
}
静态加载ConstructorHelpers
.cpp
#include"UObject/ConstructorHelpers.h"AActor::AActoe()
{
有两种,一种是FObjectFinder,另一种是FClassFinder
static ConstructorsHelpers::FObjectFinder<USkeleltalMesh>GameCharacterSkeletal(TEXT("SkeletalMesh'/Game/PolygonTown/Meshes/Characters/SK_Character_Son_01.SK_Character_Son_01'"));
//加载模型物体等用object,这样写没错。
static ConstructorHelper::FClassFinder<UAnimInstance>Gameinstance(TEXT("AnimBlueprint'/Game/Character/NewAnimBlueprint.NewAnimBlueprint_C'"));
//这个ClassFinder如果按FObjectFinder写会错误提示找不到类,需要在位置最后面增加_C,或者把位置写成/Game/Character/NewAnimBlueprint
而且有个问题就是你要定义这个位置的类给到C++必须在后面写到.Object和.Class
if(GameCharacterSkeletal.Succeeded())
{GetMesh->SetSkeletalMesh(GameCharacterSkeletal.Object);
GetMesh->SetAnimInstanceClass(Baseinstance.Class);
}}
Gamemode中定义Character等类
static ConstructorHelpers::FClassFinder<ABaseCharacter>BaseCharacter(TEXT("你类的地址"));
if(BaseCharacter.Succeeded())
{
DefaultPawnClass=BaseCharacter.Class;
}
或者动态加载
UBaseCharacterAnimInstance*MeshAnim=LoadObject<UBaseCharacterAnimInstance>(NULL,TEXT("/Game/Character/NewAnimBlueprint.NewAnimBlueprint"));
GetMesh()->SetAnimInstanceClass(MeshAnim);
在C++中,你写了一个函数,你想在搜索的时候用关键字就可以找到他,或者你想把C++中函数的名字在蓝图中以别的名字表达出来可以用meta来实现
UFUNCTION(BlueprintCallable,meta=(DisplayName="hhh"),Keywords="GGG")
void SEE();
在蓝图中输入关键字GGG就找到函数名hhh
UMG 的组件指定
.h
#include"Components/Button.h"
UPROPERTY()
UButton*StartButton;
Virtual bool Initialize()override;.cpp
bool UStartUserWidget::Initialize()
{if (!Super::Initialize()){return false;}StartButton = Cast<UButton>(GetWidgetFromName(TEXT("Button_Start")));return true;
}
游戏退出
.h
#include"Kismet/KismetSystemLibrary.h"
.cpp
UKismetSystemLibrary::QuitGame(GetWorld(),nullptr,EQuitPreference::Quit);
UE4委托DECLARE_DELEGATE使用
.h
/**在头文件的首部写入定义*/
DECLARE_DELEGATE(MyDelegate)
DECLARE_DELEGATE_OneParam(MyDelegate,int32)后在进行声明和回调函数实现,要加入UFUNCTION进行函数修饰声明,委托是参与UE的反射系统中
MyDelegate MyDe;
UFUNCTION()
void HuiDiao();
.cpp
void 父类::HuiDiao()
{}在BeginPlay中加入委托绑定
void 父类::BeginPlay()
{Super::BeginPlay();MyDe.BindUFunction(this,FName("HuiDiao"));
}
在UE4中,当你需要用到网络时,可以用HTTP发送Json数据给到WEB服务器或者用socket中的UDP和TCP两个协议来发送数据到服务器,HTTP的方式如下:
1,在项目Build.cs文件里面添加"HTTP","Json"
using UnrealBuildTool;public class RealityGame : ModuleRules
{public RealityGame(ReadOnlyTargetRules Target) : base(Target){PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore","Json","HTTP" });PrivateDependencyModuleNames.AddRange(new string[] { });// Uncomment if you are using Slate UI// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });// Uncomment if you are using online features// PrivateDependencyModuleNames.Add("OnlineSubsystem");// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true}
}
然后在你的类中写入用到的函数
.h
#include "Runtime/Online/HTTP/Public/HttpModule.h"
#include "Runtime/Online/HTTP/Public/Interfaces/IHttpRequest.h"
#include "Runtime/Online/HTTP/Public/Interfaces/IHttpResponse.h"//用户登录的方法
UFUNCTION()
void AccountLoginFromServer(FString Nickname,FString Password);
//回调函数,请求响应
void RequestComplete(FHttpRequestPtr RequestPtr,FHttpResponsePtr ResponsePtr,bool bIsSuccess);
.cpp
void 你的函数::AccountLoginFromServer()
{
//创建一个数据包先
FString Data;
//创建一个JsonWriter写入器,等下用他的函数来发送
TSharedRef<TJsonWriter<TCHAR,TCondensedJsonPrintPolicy<TCHAR>>>JsonWriter=TJsonWriterFactory<TCHAR,TCondensedJsonPrintPolicy<TCHAR>>::Create(&Data);
/*打开写入器*/JsonWriter->WriteObjectStart();/*写入昵称*/JsonWriter->WriteValue("nickname",Nickname);/*写入密码*/JsonWriter->WriteValue("password", Password);/*关闭写入*/JsonWriter->WriteObjectEnd();/*关闭json写入器*/JsonWriter->Close();/** 创建HTTP请求 */TSharedRef<IHttpRequest>Request = FHttpModule::Get().CreateRequest();/** 设置请求头 */Request->SetHeader("Content-Type", "application/json;charset=utf-8");/** 设置请求方式 */Request->SetVerb("POST");/** 设置请求的内容 */Request->SetContentAsString(Data);/** 请求的URL */Request->SetURL("http://192.168.191.1:7900/user/login-user");/** 设置请求成功的回调方法 */Request->OnProcessRequestComplete().BindUObject(this,&ULoginUserWidget::RequestComplete);/** 开始处理请求 */Request->ProcessRequest();
}/** 请求的响应方法 */
void ULoginUserWidget::RequestComplete(FHttpRequestPtr RequestPtr, FHttpResponsePtr ResponsePtr, bool bIsSuccess)
{ /** 加载框设置隐藏 */CircularThrobber->SetVisibility(ESlateVisibility::Hidden);/** 设置登录按钮可用状态 */LoginButton->SetIsEnabled(true);/** 判断响应的状态 */if (!EHttpResponseCodes::IsOk(ResponsePtr->GetResponseCode())){return;}/** 创建Json解析器 */TSharedRef<TJsonReader<TCHAR>>JsonReader = TJsonReaderFactory<TCHAR>::Create(ResponsePtr->GetContentAsString());/** 创建Json对象 */TSharedPtr<FJsonObject>JsonObject;/** 反序列化Json */bool bIsOk = FJsonSerializer::Deserialize(JsonReader, JsonObject);/** 判断是否反序列化成功 */if (bIsOk){ /** 获取返回数据的msg */FString Msg = JsonObject->GetStringField("msg");/** 获取返回的数据的data */TSharedPtr<FJsonObject>JsonData = JsonObject->GetObjectField("data");/** 从data中获取用户的id */FString Id = JsonData->GetStringField("id");/** 从data中获取用户的nickname */FString NickName = JsonData->GetStringField("nickname");}
这篇关于UE4C++笔记(_杰森大师)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!