我应该使用静态类来存储数据吗?

时间:2018-08-20 18:43:20

标签: c# unity3d

我很难为rpg游戏存储和访问数据。

现在,我需要存储一些经常访问的常量,并且应该是全局的。我所做的是创建一个包含所有常量的静态类。

public static class IndexOf
{
    public class Element
    {
        // Element ids in sprite array.
        public const int Water = 0;
        public const int Lava = 1;
        public const int Ice = 2;
    }

    public class Nature
    {
        // Nature (placed on tile)
        public const int Rock = 0;
        public const int Bush = 1;
    }

    public class Biome
    {
        //Biomes ids.
        public const int Mountain = 0;
        public const int River = 1;
    }
}

但是,有没有更好的方法或者这是一个好的解决方案?

4 个答案:

答案 0 :(得分:5)

我认为更好的选择(代码将更具可读性和可维护性)是切换到enum

  public enum Element {
    Water = 0,
    Lava = 1,
    Ice = 2, 
  };

  public enum Nature {
    Rock = 0,
    Bush = 1,
  };

  public enum Biome {
    Moutain = 0,
    River = 1,
  };

enum

  1. 更多可读enum是专门设计用于保存常量的)
  2. 已键入,因此您将永远不会像int biome = Nature.Rock;那样出错,因为Biome biome = Nature.Rock;无法编译。
  3. 更容易被修改 (将新的项目,例如将Sand添加到Nature

答案 1 :(得分:2)

您是否考虑过将常量转换为枚举?

public enum Element
{
    // Element ids in sprite array.
    Water,
    Lava,
    Ice
}

public enum Nature
{
    // Nature (placed on tile)
    Rock,
    Bush
}

public enum Biome
{
    //Biomes ids.
    Mountain,
    River
}

然后,您可以像访问任何枚举一样访问元素(Element.WaterBiome.River等)。

答案 2 :(得分:0)

对于常量值,您可以看一下枚举:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum。 枚举是一组恒定的整数,易于读取和扩展。

如果您需要一个实际的例子,请告诉我。

答案 3 :(得分:0)

我在另一个StackExchange网站上做了a very similar question,说明在游戏中存储数据的最佳方法是什么。那里有一个非常详细的答案,但总而言之,这是您在游戏中存储数据的选项:

  • 静态脚本
  • 保存数据的GameObject
  • PlayerPrefs
  • 单一模式

很大程度上取决于您要如何管理数据,是否要在场景之间停留,要多久读取一次数据或其他因素。

没有一个黄金解决方案。您必须分析用例,然后选择最适合您的选项。