You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:01:10