【问题标题】:Unity & C# - Choosing a random string from an arrayUnity & C# - 从数组中选择一个随机字符串
【发布时间】:2020-11-01 06:27:15
【问题描述】:

我正在尝试制作一个简单的石头剪刀布游戏。我需要计算机从 ROCK、PAPER 和 SCISSORS 数组中随机选择一个字符串。这是我目前所拥有的:

public string GetComputerChoice()
    {
        string computerChoice = null;
        string[] computerChoices = { "ROCK", "PAPER", "SCISSORS" };

        return computerChoice[Random.Next(computerChoices.Length)];
    }

我在 Visual Studio 中遇到的唯一错误是“下一个”,它显示“随机不包含“下一个”的定义。

我对整个编程完全陌生。关于为什么这不起作用或我可以做些什么来使它起作用的任何提示? 我已经阅读了类似帖子的其他回复,但似乎所有答案都只是代码块,无法解释其工作原理。

【问题讨论】:

  • 我怀疑 System.RandomUnityEngine.Random 的命名空间冲突 ...您可以使用 Random.Range(0, computerChoices.Length)
  • 这也回答了你的问题:stackoverflow.com/questions/2019417/…?

标签: c# arrays string unity3d random


【解决方案1】:

Next() 方法不是静态的,因此您需要实例化一个 Random 对象才能使用它:

public string GetComputerChoice()
{
    string computerChoice = null;
    string[] computerChoices = { "ROCK", "PAPER", "SCISSORS" };

    return computerChoice[new Random().Next(computerChoices.Length)];
}

但是,每次需要随机值时都创建一个新的 Random 对象并不是最佳做法,并且可能会导致意外结果(例如重复值),尤其是在快速连续调用时,因为 PRNG 种子中使用了当前时间价值(阅读pseudo random number generators 的工作原理)。理想情况下,您会创建一个 Random 对象并将其存储在某个地方以供重复使用。

我对 Unity 一点也不熟悉,但它看起来有自己的 Random 类来帮助你:Unity Random - Documentation

【讨论】:

  • 对于每一帧的使用,Unitys 随机实现也是推荐的
【解决方案2】:

你应该替换下面的行

return computerChoice[Random.Next(computerChoices.Length)];

这条线

return computerChoice[new Random().Next(computerChoices.Length)];

为什么?:
因为 Random 是一个 static 类,您不能通过 new 关键字创建它的实例。 原因是静态类在线程(包含您的请求的上下文)和发出请求的 user a 之间共享,exactlysame class 在同一 memory locationuser b 使用它。

你可以把静态类看成是多个家庭都在使用的shared room,它不只是你的,那么你无权做任何改变,你可以使用它!

当你在你的代码中使用new关键字时,实际上你是making an instance of that classthat just belong to you(你:意味着你提出的请求)。

【讨论】:

  • 这很有帮助。我很感激!
猜你喜欢
  • 1970-01-01
  • 2017-01-12
  • 2020-10-04
  • 2011-11-13
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多