Unity中随机种子在游戏关闭后生成值不一致的问题求助
问题:水排序解谜游戏关卡生成种子不一致问题
我正在开发一款类似水排序的解谜游戏,作为项目唯一开发者,我采用随机种子实现随机关卡生成器。原本功能正常,但发现游戏关闭后,随机种子生成的值会发生变化,导致后续生成的所有关卡都与之前不同,这不符合我的需求。以下是用于颜色选取的代码片段,瓶子数量等其他模块也采用相同逻辑。
补充说明
- 由于在另一个线程中生成关卡,无法使用常规的
Random.Range - 生成的数值会保存到JSON文件中,并在
Awake方法中读取
代码片段
LevelColorController.cs
public class LevelColorController : MonoBehaviour { private int GetRandomColorIndex(Data data) { var hashString = "GetRandomColor " + data.GetColorPickerRandomIndex().ToString(); var rand = new Unity.Mathematics.Random((uint)hashString.GetHashCode()); var randomColorIndex = rand.NextInt(0, _myColorsList.Count); Debug.Log(randomColorIndex); return randomColorIndex; } }
Data.cs
[System.Serializable] public class Data { public long ColorPickerRandomIndex = 0; private int _increaseVal = 50; public long GetColorPickerRandomIndex() { ColorPickerRandomIndex += _increaseVal; return ColorPickerRandomIndex - _increaseVal; } }
LevelMaker.cs
public class LevelMaker : MonoBehaviour { public Data Data; private void Awake() { JsonManager.TryGetLevelCreateDataFromJson(ref Data); } }
JsonManager.cs
public static class JsonManager { public static void TryGetLevelCreateDataFromJson(ref Data data) { var path = Paths.LevelCreationDataPath; if (File.Exists(path)) { var json = File.ReadAllText(path); data = JsonUtility.FromJson<Data>(json); } else { Debug.Log("Data not exists. Creating new one"); var json = JsonUtility.ToJson(data); File.WriteAllText(path, json); } } }
额外说明
我更新ColorPickerRandomIndex是为了增加一点随机性。
(附截图:无关闭操作时的输出、游戏运行时关闭Unity的操作示意、关闭后的输出)
内容的提问来源于stack exchange,提问作者Beytullah Kalay
相关产品推荐
相关产品推荐

