Unity&C#-从数组中选择随机字符串

时间:2020-07-11 17:34:02

标签: c# arrays string unity3d random

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

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

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

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

我对整个编程完全陌生。为什么这不起作用或我可以做些什么来使它起作用? 我已经阅读过类似文章的其他回复,但似乎所有答案都只是使它们起作用的代码块,而没有解释其起作用的原因。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您应该替换下面的行

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

在此行

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

为什么?:
由于Random是static类,因此无法通过new关键字为其创建实例。 原因是在线程(包含您的请求的上下文)和使请求使用user aexactly的{​​{1} }}使用它。

您可以将静态类视为same class,表明有多个家族在使用它,而它不仅仅属于您,那么您无权进行任何更改,您只能使用它!

当您在代码中使用memory location关键字时,实际上您就是user b shared room(您:表示您的要求)。