【问题标题】:Simplify script for my INT in every level在每个级别为我的 INT 简化脚本
【发布时间】:2020-09-02 17:06:38
【问题描述】:

我正在尝试存储 Unity 游戏中脚本“SCORE”中的 INT scoreValue 的值。

对于每个级别,它将是不同的值,目前我正在执行单独的函数 LEVEL1()、LEVEL2() 等并将该值存储在 layerPrefs.SetInt("scoreLVL1", Score.scoreValue ); & layerPrefs.SetInt("scoreLVL2", Score.scoreValue); 等等等等。

但如果我计划有 100 个关卡,我需要执行 100 个函数。

有没有更简单的方法将每个级别的所有值存储在一个函数中?

我是 Unity 的初学者,目前无法理解它。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public string nextLevel = "Level02";
    public int levelToUnlock = 2;
    public sceneFade sceneFader;
    public PauseScript pauseresume;

    public void level1()
    {
        pauseresume.levelCompletedmenu();

        if (PlayerPrefs.GetInt("levelReached") < levelToUnlock)
        {
            PlayerPrefs.SetInt("levelReached", levelToUnlock);
        }

        PlayerPrefs.SetInt("scoreLVL1", Score.scoreValue);
        PlayerPrefs.Save();
    }

    public void level2()
    {
        pauseresume.levelCompletedmenu();

        if (PlayerPrefs.GetInt("levelReached") < levelToUnlock)
        {
            PlayerPrefs.SetInt("levelReached", levelToUnlock);
        }

        PlayerPrefs.SetInt("scoreLVL2", Score.scoreValue);
        PlayerPrefs.Save();
    }
}

【问题讨论】:

  • 不要使用函数 level1(),而是使用函数 level(int levelNumber)。它应该有帮助

标签: c# unity3d


【解决方案1】:

是的,怎么样

public void level(int level)
{
    pauseresume.levelCompletedmenu();

    if (PlayerPrefs.GetInt("levelReached") < levelToUnlock)
    {
        PlayerPrefs.SetInt("levelReached", levelToUnlock);
    }
    
    PlayerPrefs.SetInt($"scoreLVL{level}", Score.scoreValue);
    PlayerPrefs.Save();
}

一般来说,我不建议使用PlayerPrefs 来存储用户进度。而是(加密和)write a fileApplication.persistentDataPath

【讨论】:

  • 我看到您不推荐 playerPrefs,但是我如何在其他脚本中调用该存储值? int levelOneWonWithPoints = PlayerPrefs.GetInt("level1"); int levelTwoWonWithPoints = PlayerPrefs.GetInt("level2"); ??
  • 怎么样? Dictionary&lt;int, int&gt; levelToPoints 所以你为每个级别存储一个条目并将其映射到点?例如。阅读var secondLevelPoints = levelToPoints[2]; 和写作levelToPoints[2] = 500;。使用例如NewtonSoft .Net Json 你可以直接(反)序列化到Dictionary
猜你喜欢
  • 2021-11-03
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多