本部分承接前三部分内容,专为熟悉 Unity C# 的资深开发者打造,全程基于Godot 4.x .NET 稳定版,覆盖游戏开发核心的 UI、资源、场景、存档四大基础架构模块,所有内容均与 Unity 开发体系 1:1 精准对标,包含完整可复用的 C# 框架代码、架构差异解析、最佳实践与避坑指南,可直接复制保存为 Markdown 文档。前置要求:已完成前三部分的环境搭建、核心编程体系、2D/3D 核心模块学习,掌握 Godot 节点树、C# 生命周期、信号系统的基础用法。


Godot 的布局系统和 UGUI 底层逻辑一致,都是基于锚点 + 边距的自适应体系,仅参数命名有差异,Unity 开发者可快速平移经验。
2.1 锚点与边距对标

2.2 高频布局预设快速适配

2.3 自动布局容器用法
Godot 的布局容器是专用节点,而非 UGUI 的附加组件,用法更简洁:
3.1 主菜单界面实现(对标 UGUI 主菜单)
代码块
using Godot;
[GlobalClass]
public partial class MainMenu : CanvasLayer
{
// 编辑器中直接拖拽绑定UI节点,对标UGUI的序列化字段
[Export] public Button StartGameBtn;
[Export] public Button SettingsBtn;
[Export] public Button QuitBtn;
[Export] public Panel SettingsPanel;
public override void _Ready()
{
// 绑定按钮点击信号,对标UGUI的onClick.AddListener
StartGameBtn.Pressed += OnStartGameClicked;
SettingsBtn.Pressed += OnSettingsClicked;
QuitBtn.Pressed += OnQuitClicked;
// 初始化隐藏设置面板
SettingsPanel.Visible = false;
}
// 开始游戏按钮点击回调
private void OnStartGameClicked()
{
GD.Print("开始游戏");
// 切换到游戏场景,详见本部分场景管理章节
GetTree().ChangeSceneToFile("res://Scenes/GameScene.tscn");
}
// 设置按钮点击回调
private void OnSettingsClicked()
{
SettingsPanel.Visible = !SettingsPanel.Visible;
}
// 退出游戏按钮点击回调
private void OnQuitClicked()
{
GD.Print("退出游戏");
GetTree().Quit();
}
// 节点销毁前解绑信号,防止内存泄漏
public override void _ExitTree()
{
StartGameBtn.Pressed -= OnStartGameClicked;
SettingsBtn.Pressed -= OnSettingsClicked;
QuitBtn.Pressed -= OnQuitClicked;
}
}
3.2 角色血条与状态 UI 实现
代码块
using Godot;
[GlobalClass]
public partial class PlayerHUD : CanvasLayer
{
[Export] public ProgressBar HealthBar;
[Export] public Label HealthText;
[Export] public Label ScoreText;
[Export] public PlayerController Player;
public override void _Ready()
{
// 绑定玩家血量变化信号,实时更新UI
Player.HealthChanged += OnHealthChanged;
Player.ScoreChanged += OnScoreChanged;
// 初始化UI
OnHealthChanged(Player.CurrentHealth, Player.MaxHealth);
OnScoreChanged(Player.Score);
}
// 血量变化回调,对标UGUI的Slider值更新
private void OnHealthChanged(int currentHealth, int maxHealth)
{
// 设置进度条最大值与当前值
HealthBar.MaxValue = maxHealth;
HealthBar.Value = currentHealth;
// 更新文本
HealthText.Text = $"{currentHealth}/{maxHealth}";
// 血量低于20%变红
HealthBar.Modulate = currentHealth < maxHealth * 0.2f ? Colors.Red : Colors.Green;
}
// 分数变化回调
private void OnScoreChanged(int score)
{
ScoreText.Text = $"分数:{score}";
}
public override void _ExitTree()
{
Player.HealthChanged -= OnHealthChanged;
Player.ScoreChanged -= OnScoreChanged;
}
}
3.3 背包滚动列表实现(对标 UGUI ScrollRect 循环列表)
代码块
using Godot;
using System.Collections.Generic;
[GlobalClass]
public partial class BackpackUI : Control
{
[Export] public ScrollContainer ScrollContainer;
[Export] public GridContainer ItemGrid;
[Export] public PackedScene ItemCellPrefab; // 背包格子预制体
[Export] public int ColumnCount = 5; // 列数
private List<ItemData> _backpackItems = new List<ItemData>();
public override void _Ready()
{
// 设置网格列数
ItemGrid.Columns = ColumnCount;
// 模拟初始化背包数据
InitBackpackData();
// 刷新背包UI
RefreshBackpackUI();
}
// 初始化背包数据
private void InitBackpackData()
{
for (int i = 0; i < 30; i++)
{
_backpackItems.Add(new ItemData
{
ItemId = i,
ItemName = $"道具{i + 1}",
ItemCount = GD.RandRange(1, 99),
IconPath = $"res://Textures/Items/item_{i}.png"
});
}
}
// 刷新背包UI
public void RefreshBackpackUI()
{
// 清空旧格子
foreach (Node child in ItemGrid.GetChildren())
{
child.QueueFree();
}
// 生成新格子
foreach (var item in _backpackItems)
{
// 实例化格子预制体
var itemCell = ItemCellPrefab.Instantiate<ItemCell>();
// 设置格子数据
itemCell.SetCellData(item);
// 绑定点击事件
itemCell.OnCellClicked += OnItemCellClicked;
// 加入网格容器
ItemGrid.AddChild(itemCell);
}
}
// 道具格子点击回调
private void OnItemCellClicked(ItemData itemData)
{
GD.Print($"点击道具:{itemData.ItemName},数量:{itemData.ItemCount}");
// 处理道具使用逻辑
}
}
// 道具数据结构体
public struct ItemData
{
public int ItemId;
public string ItemName;
public int ItemCount;
public string IconPath;
}
// 背包格子脚本
[GlobalClass]
public partial class ItemCell : Button
{
[Export] public TextureRect ItemIcon;
[Export] public Label ItemCountText;
public ItemData CurrentItemData;
// 定义点击信号
[Signal] public delegate void OnCellClickedEventHandler(ItemData itemData);
public void SetCellData(ItemData data)
{
CurrentItemData = data;
// 设置图标
ItemIcon.Texture = GD.Load<Texture2D>(data.IconPath);
// 设置数量
ItemCountText.Text = data.ItemCount.ToString();
// 绑定点击事件
Pressed += () => EmitSignal(SignalName.OnCellClicked, CurrentItemData);
}
}

2.1 同步资源加载(对标 Unity Resources.Load)
适用于小体积资源、高频使用的资源,加载时会阻塞主线程,用法和 Unity 完全一致。
代码块
using Godot;
[GlobalClass]
public partial class ResourceTest : Node
{
// 方式1:编辑器预加载(推荐,零代码,自动预加载,无运行时卡顿)
[Export] public Texture2D PlayerIcon;
[Export] public PackedScene PlayerPrefab;
[Export] public AudioStream JumpSFX;
public override void _Ready()
{
// 方式2:运行时同步加载
// 加载纹理
var weaponTexture = GD.Load<Texture2D>("res://Textures/Weapons/sword.png");
// 加载场景预制体
var bulletPrefab = GD.Load<PackedScene>("res://Prefabs/Bullet.tscn");
// 加载音频
var attackSFX = GD.Load<AudioStream>("res://Audio/SFX/attack.wav");
// 实例化预制体,对标Unity Instantiate
var bulletInstance = bulletPrefab.Instantiate<Bullet>();
AddChild(bulletInstance);
}
// 卸载资源
public void UnloadResource()
{
// 卸载单个资源
ResourceLoader.Unload(PlayerPrefab);
// 卸载所有未使用的资源
ResourceLoader.UnloadUnusedResources();
}
}
2.2 异步资源加载(带进度条,对标 Unity Addressables 异步加载)
适用于大体积资源、场景、模型,加载时不阻塞主线程,可显示加载进度,避免游戏卡顿。
代码块
using Godot;
using System.Threading.Tasks;
[GlobalClass]
public partial class AsyncResourceLoader : Node
{
[Export] public ProgressBar LoadingProgressBar;
[Export] public Label LoadingTipLabel;
// 异步加载单个资源
public async Task<T> LoadResourceAsync<T>(string resourcePath) where T : Resource
{
// 发起异步加载请求
ResourceLoader.LoadThreadedRequest(resourcePath, useSubThreads: true);
// 监听加载进度
while (ResourceLoader.LoadThreadedGetStatus(resourcePath) == ResourceLoader.ThreadLoadStatus.InProgress)
{
// 获取加载进度(0-1)
float progress = ResourceLoader.LoadThreadedGetProgress(resourcePath);
// 更新UI
LoadingProgressBar.Value = progress * 100;
LoadingTipLabel.Text = $"资源加载中:{progress * 100:F0}%";
// 等待下一帧,不阻塞主线程
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
// 加载完成,获取资源
var loadedResource = ResourceLoader.LoadThreadedGet(resourcePath) as T;
// 加载失败处理
if (loadedResource == null)
{
GD.PushError($"资源加载失败:{resourcePath}");
return null;
}
LoadingTipLabel.Text = "资源加载完成";
return loadedResource;
}
// 批量异步加载资源
public async Task BatchLoadResourcesAsync(string[] resourcePaths)
{
int totalCount = resourcePaths.Length;
int loadedCount = 0;
foreach (var path in resourcePaths)
{
await LoadResourceAsync<Resource>(path);
loadedCount++;
// 更新总进度
float totalProgress = (float)loadedCount / totalCount;
LoadingProgressBar.Value = totalProgress * 100;
}
GD.Print($"批量加载完成,共加载{totalCount}个资源");
}
}
2.3 资源对象池实现(对标 Unity 对象池,性能优化核心)
适用于高频实例化 / 销毁的对象(子弹、特效、怪物),避免频繁创建销毁节点产生的性能开销与 GC,是游戏性能优化的核心手段。
代码块
using Godot;
using System.Collections.Generic;
[GlobalClass]
public partial class GameObjectPool : Node
{
// 单例实例,全局访问
public static GameObjectPool Instance;
// 对象池字典:key=预制体路径,value=对象队列
private Dictionary<string, Queue<Node>> _poolDict = new Dictionary<string, Queue<Node>>();
// 预制体缓存字典
private Dictionary<string, PackedScene> _prefabCache = new Dictionary<string, PackedScene>();
public override void _EnterTree()
{
// 单例初始化
if (Instance == null)
{
Instance = this;
}
else
{
QueueFree();
}
}
// 初始化对象池,预生成指定数量的对象
public async void InitPool(string prefabPath, int initCount)
{
// 加载预制体并缓存
if (!_prefabCache.ContainsKey(prefabPath))
{
var prefab = await LoadResourceAsync<PackedScene>(prefabPath);
if (prefab == null) return;
_prefabCache.Add(prefabPath, prefab);
}
// 初始化队列
if (!_poolDict.ContainsKey(prefabPath))
{
_poolDict.Add(prefabPath, new Queue<Node>());
}
// 预生成对象
for (int i = 0; i < initCount; i++)
{
var instance = _prefabCache[prefabPath].Instantiate();
instance.ProcessMode = ProcessModeEnum.Disabled;
instance.Visible = false;
AddChild(instance);
_poolDict[prefabPath].Enqueue(instance);
}
GD.Print($"对象池初始化完成:{prefabPath},预生成数量:{initCount}");
}
// 从对象池获取对象
public Node SpawnObject(string prefabPath, Node parentNode, Vector2 position = default)
{
// 检查预制体是否缓存
if (!_prefabCache.ContainsKey(prefabPath))
{
GD.PushError($"预制体未初始化:{prefabPath}");
return null;
}
Node instance;
// 池中有空闲对象,直接取出
if (_poolDict[prefabPath].Count > 0)
{
instance = _poolDict[prefabPath].Dequeue();
}
// 池为空,新建对象
else
{
instance = _prefabCache[prefabPath].Instantiate();
AddChild(instance);
}
// 初始化对象
instance.ProcessMode = ProcessModeEnum.Inherit;
instance.Visible = true;
// 设置父节点与位置
instance.Reparent(parentNode);
if (instance is Node2D node2D)
{
node2D.GlobalPosition = position;
}
else if (instance is Node3D node3D)
{
node3D.GlobalPosition = new Vector3(position.X, position.Y, 0);
}
return instance;
}
// 将对象回收至对象池
public void RecycleObject(string prefabPath, Node instance)
{
// 检查池是否存在
if (!_poolDict.ContainsKey(prefabPath))
{
instance.QueueFree();
return;
}
// 重置对象状态
instance.ProcessMode = ProcessModeEnum.Disabled;
instance.Visible = false;
instance.Reparent(this);
// 加入队列
_poolDict[prefabPath].Enqueue(instance);
}
// 清空对象池
public void ClearPool()
{
foreach (var queue in _poolDict.Values)
{
while (queue.Count > 0)
{
queue.Dequeue().QueueFree();
}
}
_poolDict.Clear();
_prefabCache.Clear();
}
}

2.1 场景管理器单例(对标 Unity SceneManager 封装)
代码块
using Godot;
using System.Threading.Tasks;
[GlobalClass]
public partial class SceneManager : Node
{
// 单例实例,全局访问(需在项目设置中设置为Autoload节点)
public static SceneManager Instance;
// 当前激活的场景根节点
public Node CurrentSceneRoot { get; private set; }
// 叠加加载的场景字典
public System.Collections.Generic.Dictionary<string, Node> AdditiveScenes { get; private set; } = new();
// 加载界面场景路径
private const string LoadingScenePath = "res://Scenes/LoadingScene.tscn";
// 全局根节点
private Node _rootNode => GetTree().Root;
public override void _EnterTree()
{
// 单例初始化
if (Instance == null)
{
Instance = this;
}
else
{
QueueFree();
}
}
#region 同步场景切换
// 同步切换场景,对标Unity SceneManager.LoadScene
public void ChangeScene(string scenePath)
{
// 校验场景路径
if (!ResourceLoader.Exists(scenePath))
{
GD.PushError($"场景不存在:{scenePath}");
return;
}
// 切换场景
GetTree().ChangeSceneToFile(scenePath);
// 更新当前场景引用
CurrentSceneRoot = _rootNode.GetChild(_rootNode.GetChildCount() - 1);
GD.Print($"场景切换完成:{scenePath}");
}
#endregion
#region 异步场景切换(带加载界面与进度条)
// 异步切换场景,带加载界面,对标Unity LoadSceneAsync
public async void ChangeSceneAsync(string targetScenePath)
{
// 1. 加载并显示加载界面
var loadingScene = GD.Load<PackedScene>(LoadingScenePath).Instantiate();
_rootNode.AddChild(loadingScene);
// 2. 异步加载目标场景
var loadTask = LoadSceneAsync(targetScenePath);
var loadingUI = loadingScene.GetNode<LoadingUI>("LoadingUI");
// 3. 监听加载进度
while (!loadTask.IsCompleted)
{
loadingUI.SetProgress(loadTask.Result.Progress);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
// 4. 加载完成,获取场景资源
var targetScene = loadTask.Result.SceneResource;
if (targetScene == null)
{
GD.PushError($"场景加载失败:{targetScenePath}");
loadingScene.QueueFree();
return;
}
// 5. 销毁旧场景,实例化新场景
CurrentSceneRoot?.QueueFree();
CurrentSceneRoot = targetScene.Instantiate();
_rootNode.AddChild(CurrentSceneRoot);
// 6. 延迟0.5秒销毁加载界面,给用户看加载完成提示
await ToSignal(GetTree().CreateTimer(0.5f), SceneTreeTimer.SignalName.Timeout);
loadingScene.QueueFree();
GD.Print($"异步场景切换完成:{targetScenePath}");
}
// 异步加载场景资源,返回加载进度与资源
private async Task<(float Progress, PackedScene SceneResource)> LoadSceneAsync(string scenePath)
{
// 发起异步加载请求
ResourceLoader.LoadThreadedRequest(scenePath, useSubThreads: true);
float progress = 0;
PackedScene sceneResource = null;
// 循环检测加载状态
while (ResourceLoader.LoadThreadedGetStatus(scenePath) == ResourceLoader.ThreadLoadStatus.InProgress)
{
progress = ResourceLoader.LoadThreadedGetProgress(scenePath);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
// 加载完成
if (ResourceLoader.LoadThreadedGetStatus(scenePath) == ResourceLoader.ThreadLoadStatus.Loaded)
{
sceneResource = ResourceLoader.LoadThreadedGet(scenePath) as PackedScene;
progress = 1f;
}
return (progress, sceneResource);
}
#endregion
#region 叠加场景加载/卸载(对标Unity Additive加载)
// 叠加加载场景,不销毁当前场景
public async void LoadAdditiveScene(string scenePath)
{
// 避免重复加载
if (AdditiveScenes.ContainsKey(scenePath))
{
GD.Print($"场景已加载:{scenePath}");
return;
}
// 异步加载场景
var sceneResource = await LoadResourceAsync<PackedScene>(scenePath);
if (sceneResource == null) return;
// 实例化场景并挂载到根节点
var sceneRoot = sceneResource.Instantiate();
_rootNode.AddChild(sceneRoot);
// 加入字典管理
AdditiveScenes.Add(scenePath, sceneRoot);
GD.Print($"叠加场景加载完成:{scenePath}");
}
// 卸载叠加加载的场景
public void UnloadAdditiveScene(string scenePath)
{
if (!AdditiveScenes.TryGetValue(scenePath, out var sceneRoot))
{
GD.PushError($"场景未加载:{scenePath}");
return;
}
// 销毁场景节点
sceneRoot.QueueFree();
// 从字典移除
AdditiveScenes.Remove(scenePath);
GD.Print($"叠加场景卸载完成:{scenePath}");
}
#endregion
}
// 加载界面UI脚本
[GlobalClass]
public partial class LoadingUI : Control
{
[Export] public ProgressBar ProgressBar;
[Export] public Label TipLabel;
public void SetProgress(float progress)
{
ProgressBar.Value = progress * 100;
TipLabel.Text = $"场景加载中:{progress * 100:F0}%";
}
}
2.2 常驻节点与 Autoload 配置(对标 Unity DontDestroyOnLoad)
Godot 的 Autoload 自动加载节点是实现全局单例、常驻管理器的最佳方案,切换场景时永远不会被销毁,无需手动调用 DontDestroyOnLoad。
配置步骤:

2.1 全局设置存档(ConfigFile,对标 Unity PlayerPrefs)
用于存储游戏设置、音量、画质、按键绑定等轻量级键值对数据,用法比 PlayerPrefs 更灵活。
代码块
using Godot;
[GlobalClass]
public partial class SettingsSave : Node
{
// 单例实例,Autoload节点
public static SettingsSave Instance;
// 配置文件实例
private ConfigFile _configFile = new ConfigFile();
// 存档文件路径
private const string SaveFilePath = "user://settings.save";
// 配置分组与键名常量
private const string AudioGroup = "Audio";
private const string GraphicsGroup = "Graphics";
private const string InputGroup = "Input";
public override void _EnterTree()
{
if (Instance == null)
{
Instance = this;
}
else
{
QueueFree();
}
// 启动时加载存档
LoadSettings();
}
#region 加载与保存
// 加载设置存档
public void LoadSettings()
{
// 检查存档文件是否存在
if (!FileAccess.FileExists(SaveFilePath))
{
GD.Print("设置存档不存在,使用默认设置");
SetDefaultSettings();
return;
}
// 加载存档文件
var error = _configFile.Load(SaveFilePath);
if (error != Error.Ok)
{
GD.PushError($"设置存档加载失败,错误码:{error}");
SetDefaultSettings();
return;
}
GD.Print("设置存档加载完成");
}
// 保存设置存档
public void SaveSettings()
{
var error = _configFile.Save(SaveFilePath);
if (error != Error.Ok)
{
GD.PushError($"设置存档保存失败,错误码:{error}");
return;
}
GD.Print("设置存档保存完成");
}
// 设置默认设置
private void SetDefaultSettings()
{
SetMasterVolume(1f);
SetBGMVolume(1f);
SetSFXVolume(1f);
SetFullScreen(true);
SetResolution(1920, 1080);
SaveSettings();
}
#endregion
#region 音频设置
public float GetMasterVolume()
{
return (float)_configFile.GetValue(AudioGroup, "MasterVolume", 1f);
}
public void SetMasterVolume(float value)
{
_configFile.SetValue(AudioGroup, "MasterVolume", value);
}
public float GetBGMVolume()
{
return (float)_configFile.GetValue(AudioGroup, "BGMVolume", 1f);
}
public void SetBGMVolume(float value)
{
_configFile.SetValue(AudioGroup, "BGMVolume", value);
}
public float GetSFXVolume()
{
return (float)_configFile.GetValue(AudioGroup, "SFXVolume", 1f);
}
public void SetSFXVolume(float value)
{
_configFile.SetValue(AudioGroup, "SFXVolume", value);
}
#endregion
#region 画面设置
public bool GetFullScreen()
{
return (bool)_configFile.GetValue(GraphicsGroup, "FullScreen", true);
}
public void SetFullScreen(bool isFullScreen)
{
_configFile.SetValue(GraphicsGroup, "FullScreen", isFullScreen);
}
public Vector2I GetResolution()
{
int width = (int)_configFile.GetValue(GraphicsGroup, "ResolutionWidth", 1920);
int height = (int)_configFile.GetValue(GraphicsGroup, "ResolutionHeight", 1080);
return new Vector2I(width, height);
}
public void SetResolution(int width, int height)
{
_configFile.SetValue(GraphicsGroup, "ResolutionWidth", width);
_configFile.SetValue(GraphicsGroup, "ResolutionHeight", height);
}
#endregion
}
2.2 游戏存档系统(JSON 结构化存档,支持多存档槽、加密)
用于存储玩家进度、角色数据、关卡进度、背包数据等复杂结构化数据,支持多存档槽、数据校验、自动备份,是商业游戏的标准存档方案。
代码块
using Godot;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
// 玩家存档数据结构体(可根据游戏需求扩展)
[Serializable]
public class GameSaveData
{
// 基础信息
public int SaveSlotId;
public string SaveTime;
public int PlayTimeSeconds;
// 玩家数据
public int PlayerLevel;
public int CurrentHealth;
public int MaxHealth;
public int Score;
public Vector2 PlayerPosition;
// 背包数据
public List<ItemData> BackpackItems;
// 关卡进度
public int UnlockedLevelCount;
public int CurrentLevelId;
}
[GlobalClass]
public partial class GameSaveManager : Node
{
// 单例实例,Autoload节点
public static GameSaveManager Instance;
// 存档文件加密密钥(自行修改,16位字符)
private const string EncryptKey = "GodotSave123456";
// 存档文件路径前缀
private const string SaveFilePrefix = "user://game_save_";
// 存档文件后缀
private const string SaveFileSuffix = ".sav";
// 最大存档槽数量
public const int MaxSaveSlotCount = 5;
// JSON序列化配置
private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { WriteIndented = true };
public override void _EnterTree()
{
if (Instance == null)
{
Instance = this;
}
else
{
QueueFree();
}
}
#region 存档核心方法
// 保存游戏存档到指定槽位
public bool SaveGame(int slotId, GameSaveData saveData)
{
// 校验槽位
if (slotId < 0 || slotId >= MaxSaveSlotCount)
{
GD.PushError($"存档槽位无效:{slotId}");
return false;
}
try
{
// 补充存档基础信息
saveData.SaveSlotId = slotId;
saveData.SaveTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// 1. 序列化为JSON字符串
string jsonData = JsonSerializer.Serialize(saveData, _jsonOptions);
// 2. AES加密
string encryptedData = AesEncrypt(jsonData, EncryptKey);
// 3. 写入文件
string filePath = $"{SaveFilePrefix}{slotId}{SaveFileSuffix}";
using var file = FileAccess.Open(filePath, FileAccess.ModeFlags.Write);
file.StoreString(encryptedData);
GD.Print($"存档保存成功,槽位:{slotId},路径:{filePath}");
return true;
}
catch (Exception e)
{
GD.PushError($"存档保存失败:{e.Message}");
return false;
}
}
// 加载指定槽位的游戏存档
public GameSaveData LoadGame(int slotId)
{
// 校验槽位
if (slotId < 0 || slotId >= MaxSaveSlotCount)
{
GD.PushError($"存档槽位无效:{slotId}");
return null;
}
// 检查存档文件是否存在
string filePath = $"{SaveFilePrefix}{slotId}{SaveFileSuffix}";
if (!FileAccess.FileExists(filePath))
{
GD.Print($"存档槽位{slotId}无存档");
return null;
}
try
{
// 1. 读取文件
using var file = FileAccess.Open(filePath, FileAccess.ModeFlags.Read);
string encryptedData = file.GetAsText();
// 2. AES解密
string jsonData = AesDecrypt(encryptedData, EncryptKey);
// 3. 反序列化为存档数据
var saveData = JsonSerializer.Deserialize<GameSaveData>(jsonData, _jsonOptions);
GD.Print($"存档加载成功,槽位:{slotId}");
return saveData;
}
catch (Exception e)
{
GD.PushError($"存档加载失败:{e.Message}");
return null;
}
}
// 删除指定槽位的存档
public bool DeleteSave(int slotId)
{
string filePath = $"{SaveFilePrefix}{slotId}{SaveFileSuffix}";
if (!FileAccess.FileExists(filePath))
{
GD.Print($"存档槽位{slotId}无存档,无需删除");
return false;
}
DirAccess.RemoveAbsolute(filePath);
GD.Print($"存档删除成功,槽位:{slotId}");
return true;
}
// 获取所有存档槽位的信息
public GameSaveData[] GetAllSaveInfos()
{
var saveInfos = new GameSaveData[MaxSaveSlotCount];
for (int i = 0; i < MaxSaveSlotCount; i++)
{
saveInfos[i] = LoadGame(i);
}
return saveInfos;
}
// 创建新的空白存档数据
public GameSaveData CreateNewSaveData()
{
return new GameSaveData
{
PlayerLevel = 1,
CurrentHealth = 100,
MaxHealth = 100,
Score = 0,
PlayerPosition = Vector2.Zero,
BackpackItems = new List<ItemData>(),
UnlockedLevelCount = 1,
CurrentLevelId = 1,
PlayTimeSeconds = 0
};
}
#endregion
#region AES加密解密工具方法
// AES加密
private string AesEncrypt(string plainText, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.PadRight(16).Substring(0, 16));
using Aes aes = Aes.Create();
aes.Key = keyBytes;
aes.Mode = CipherMode.CBC;
aes.IV = keyBytes;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using MemoryStream ms = new MemoryStream();
using CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
using StreamWriter sw = new StreamWriter(cs);
sw.Write(plainText);
sw.Close();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
// AES解密
private string AesDecrypt(string cipherText, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.PadRight(16).Substring(0, 16));
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using Aes aes = Aes.Create();
aes.Key = keyBytes;
aes.Mode = CipherMode.CBC;
aes.IV = keyBytes;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using MemoryStream ms = new MemoryStream(cipherBytes);
using CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
using StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
#endregion
}
第五部分将完整讲解:
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删