Random variable values?

Hello, is there any way to randomly assign a (float) variables values between a minimum and a max?

What I tried is to have a float like public float example = 20f and generate a random range in the start function, variablize it, and then instead do public float example = "variable"

Another user told me this for a similar project, and it worked, but when I apply it now, it says “variable” does not exist in the current context.
This is probably because the public float is assigned before the random number is varablized, but when I try to move it after the start function, even more errors appear. Is there any code to work around this?


What the heck do you mean by “varablized”? A variable is a named piece of memory. Variables can not be created dynamically. Your example also doesn’t make much sense. When you have a member variable like this:

public float example = initialValue;

the field initializer (the = initialValue part) is executed before the constructor of the class actually runs and therefore long before any Start method might be called. Your next issue is that the field initializer is only used once for serialized fields- Since serialized fields get their value serialized in the inspector. So, once serialized, the value you assign in the field initializer becomes meaningless since it’s overwritten by the serialized value anyways.

Why don’t you just roll your random value in Start and assign it to the variable of your choice? In your case “example” IS your target variable.

Get Random variable values

var randomValue = Random.Range(min, max);

Get Random enum type

    public static T RandomEnum<T>()   
        Array values = Enum.GetValues(typeof(T));   
        return (T)values.GetValue(new System.Random().Next(0, values.Length));