How do you randomize numbers inside of your own class constructor?

Every time I use this code:

using System.Collections;
using System.Collections.Generic;

public class Character : MonoBehaviour {

	public string sex;
	public string race;
	public int intelligence;
	public int strength;
	public int charisma;

	private int maxStats = 10;
	private int rand;



	public Character()
	{
		rand = Random.Range (0, 2);

		if (rand == 1) {
			sex = "Male";
		} else {
			sex= "Female";
		}

		rand = Random.Range (0, 3);

		if (rand == 0) {
			race = "Elf";
		} else if (rand == 1) {
			race = "Human";
		} else {
			race = "Orc";
		}

		for (int x = 0; x < maxStats; x++) {
			rand = Random.Range (0, 3);

			if (rand == 0) {
				intelligence += 1;
			} else if (rand == 1) {
				strength += 1;
			} else {
				charisma += 1;
			}
		}
	}
}

I get an error that says:

RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour ‘Character’ on game object ‘GameObject’.

How can I randomize the numbers inside of this constructor?

Most of Unity’s methods can only be used in Unity’s main thread, so in places like Awake, Start, Update etc.

Also, your class Character is a Monobehaviour. Monobehaviours aren’t really supposed to have a constructor, so removing that constructor and moving everything to Start/Awake is the right thing to do.

But, if you DO want to get Randomized values for another class that’s not a Monobehaviour, you can use the native Random, like this.

Random r = new Random();

rand = r.Next (0, 3);
 
         if (rand == 0) {
             race = "Elf";
         } else if (rand == 1) {
             race = "Human";
         } else {
             race = "Orc";
         }