Search code examples
c#stringunity-game-enginerandomvoid

Problems with Unity Random Function


Good evening, I was working on a graphic adventure and I want to make a random function with a 4 digit code, turns out that as I am a very novice programmer, I crashed with an inconvenient

private void CheckResults()
{
    if (codeSequence = RandomCode.RanCode.ToString())
        {
    SoundManager.PlaySound("nice");
    }

else
{
    SoundManager.PlaySound("wrong");
}   

"RandomCode.RanCode" is a int void, and adding "ToString" will shot an error saying

"RanCode is a method which is not valid in the given context"

This is the RandomCode void:

 public void RanCode()
{
    Code = Random.Range(1111, 9999);
}

If anyone out there has any ideas or solves, I will be eternally grateful


Solution

  • There's no such thing as an "int void". A method either returns nothing (void) or returns a value (in your case you seem to expect int).

    //   Returns nothing
    //      |
    //      v
    public void RanCode()
    {
        // assigns result of `Range` to `Code` property/field
        Code = Random.Range(1111, 9999);
    }
    

    If you want to also return the value, you need to rewrite your method like this:

    public int RanCode()
    {
        Code = Random.Range(1111, 9999);
        return Code;
    }
    

    You do have another issue here:

    RandomCode.RanCode.ToString()
    

    To call a method you need (), so it should be this:

    RandomCode.RanCode().ToString()
    

    Also, for equality checks you want == not = (which is assignment).

    I do wonder why you're assigning a value to Code here. If we use your existing code (without my fix above), I guess that perhaps you intended something like this instead?:

    private void CheckResults()
    {
        RandomCode.RanCode();   
        if (codeSequence == RandomCode.Code.ToString())
        {
            SoundManager.PlaySound("nice");
        }
        else
        {
            SoundManager.PlaySound("wrong");
        }   
    }