- Home /
Random number not printing in console?
I am very new to Unity and have little experience in C#. In my code I am trying to generate a random number, then have the Console print it. I have googled this problem a lot but still cannot find a solution. Any suggestions? (Everything is enabled in the console).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LaserShooter : MonoBehaviour {
public static System.Random rand = new System.Random();
public int modChoose = rand.Next(1,4);
void Start () {
}
void Update () {
Debug.Log (modChoose);
}
}
Answer by Commoble · Mar 12, 2017 at 04:57 PM
First, an explanation:
In Unity, when you make a class that derives from MonoBehaviour and add it to a GameObject as a script component, each of your public variables become visible in the Inspector for that GameObject. When the game starts and the scene loads up and the object initializes and all the scripts on that object initialize, unity takes all the values that were set in the Inspector and sets all your public variables' values to those values. This means that when you set your public variable's values when you declare them:
public int modChoose = rand.Next(1,4);
then this random value will be overwritten by the Inspector values.
Whenever you need to initialize a variable based on some function, you should set it in the Awake or Start event:
void Awake()
{
this.modChoose = rand.Next(1,4);
}
Additionally, whenever you have a variable that you don't want to set in the inspector, you should prevent it from appearing in the inspector in the first place to avoid confusion. You can do this by setting the variable to private, or using [System.NonSerialized]:
private int modChoose;
// or:
[System.NonSerialized] public int modChoose;
[HideInInspector] public int modChoose;
also works..Good thing about Unity. there is a hundred different ways to skin a cat
Never $$anonymous$$d, I used your solution and it was still not working. The reason was I didn't assign the script to a Game Object. Thank you for responding though!
Your answer
![](https://koobas.hobune.stream/wayback/20220612112755im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Need help with random spawning system. 1 Answer
pick a random int with the value of 1 from an array 2 Answers
Accessing local system ( File Browser ) 2 Answers
Lottery system 1 Answer