本篇文章主要是做功能演示和教程 这为了方便所以使用按键输入进行操作
1.绑定输入按键 打开UE4项目设置->找到Input(输入)->绑定事件
2.创建C++ SaveGame类
3.在C++ SaveGame类内创建出需要的保存的变量
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "MySaveGame.generated.h"
/**
*
*/
UCLASS()
class FPS_API UMySaveGame : public USaveGame
{
GENERATED_BODY()
public:
UMySaveGame();
UPROPERTY(EditAnywhere)
FVector PlayerLoction;
};
CPP文件
// Fill out your copyright notice in the Description page of Project Settings.
#include "MySaveGame.h"
UMySaveGame::UMySaveGame()
{
PlayerLoction = FVector(0.f, 0.f, 0.f);
}
4.在Character内创建两个函数 分别为保存函数和加载函数
5.在事件绑定内创建绑定事件
PlayerInputComponent->BindAction("Save", IE_Pressed, this, &AfpSCharacter::SaveGame);
PlayerInputComponent->BindAction("Load", IE_Pressed, this, &AfpSCharacter::LoadGame);
6.保存 加载功能
void AfpSCharacter::SaveGame()
{
UMySaveGame * SaveGameInstance = Cast<UMySaveGame>(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
SaveGameInstance->PlayerLoction = this->GetActorLocation();//设置保存位置
UGameplayStatics::SaveGameToSlot(SaveGameInstance, TEXT("MySlot"),0);
GEngine->AddOnScreenDebugMessage(-1,5, FColor::Green, TEXT("Game Saved"));
}
void AfpSCharacter::LoadGame()
{
UMySaveGame * SaveGameInstance = Cast<UMySaveGame>(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
SaveGameInstance =Cast<UMySaveGame>( UGameplayStatics::LoadGameFromSlot("MySlot", 0));
this->SetActorLocation(SaveGameInstance->PlayerLoction); //更新位置
GEngine->AddOnScreenDebugMessage(-1, 5, FColor::Green, TEXT("Load Game"));
}```
效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/89523a68302b425babb8883000e93af9.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARXpfY29kZXI=,size_20,color_FFFFFF,t_70,g_se,x_16)
![在这里插入图片描述](https://img-blog.csdnimg.cn/c903d053b25e4d1b9b338427865223ac.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARXpfY29kZXI=,size_20,color_FFFFFF,t_70,g_se,x_16)