首页 > 解决方案 > 如何保存使用 Random.Range 显示的答案字符串并链接到成就

问题描述

我一直在尝试为此找到解决方案,但被卡住了,因此非常感谢任何建议。

现在,我有一个列表,用于使用 Random.Range 向用户随机显示列表中的字符串。但是,这些答案不会被记录或保存,因此用户无法知道他们解锁了多少这些答案。

这就是我现在所拥有的:

List<string> allLocations = new List<string>();

allLocations.Insert(0, "Answer 1");
allLocations.Insert(1, "Answer 2");
allLocations.Insert(2, "Answer 3");

 // Display random answer from list

string displayAnswer = allLocations[Random.Range(0, allLocations.Count)];

如果之前没有向用户显示过,我想实现一种方法来记录每个显示的字符串,并根据不同的类别对列表(或更合适的选项)中的字符串进行排序。

例如,如果显示了“答案1”或“答案2”中的任何一个字符串,并且之前没有显示给用户,则将其记录并计为成就A类解锁的一个答案。如果字符串“Answer 3”第一次显示给用户,则将其计为 B 类解锁答案。

理想情况下,我可以对这些未锁定的答案字符串进行排序,以便用户可以看到他们在每个类别中解锁了多少答案。这些解锁的答案共有 101 个字符串,分为 10 个成就类别。

如何实现这一点,并使以前显示给用户的字符串记录可以访问显示成就的脚本?我读到 JSON 数据序列化比 PlayerPrefs 更好,但我不确定如何实现这一点。

谢谢!如果这是一个愚蠢的问题,我提前道歉;我对 Unity 和 C# 真的很陌生。

标签: c#listunity3d

解决方案


您可以封装有关视图计数/类别的数据,并以通用方式使用这些集合。例如,您可以使用如下行为:

public class Answer
{
    public string Text;
    public string Category;
    public int ViewsCount;
}

public class AnswersCollection
{
    private readonly List<Answer> _answers = new List<Answer>();

    /// <summary>
    /// to init data
    /// </summary>
    public void AddAnswer(string text, string category)
    {
        _answers.Add(new Answer {Text = text, Category = category, ViewsCount = 0});
    }


    public string GetNoViewedRandomAnswer(bool setViewed = true)
    {
        var some = _answers.Where(a => a.ViewsCount == 0)
            .OrderBy(_ => Guid.NewGuid()) // to randomize collection ordering
            .FirstOrDefault();
        if (some != null && setViewed) some.ViewsCount++;
        return some.Text;
    }

    public string[] GetViewedCategories() =>
        _answers.Where(a => a.ViewsCount > 0).Select(a => a.Category).ToArray();

    public string[] GetViewedAnswers() =>
        _answers.Where(a => a.ViewsCount > 0).Select(a => a.Text).ToArray();

    public System.Tuple<string, string>[] GetViewedAnswersWithCategory() =>
        _answers.Where(a => a.ViewsCount > 0).Select(a => Tuple.Create(a.Text, a.Category)).ToArray();
}

推荐阅读