- Home /
Random.Range always returns min value (didn't set seed)
using UnityEngine; using System.Collections;
public class PrefabSpawn : MonoBehaviour {
public GameObject[] items;
int X = Random.Range(0,2);
void Awake()
{
Instantiate (items[X], new Vector3(0,0,0), Quaternion.identity);
}
void Update () {
}
}
Here's my code, it's supposed to spawn a prefab from a table, but it always spawns the one stored in items[0]. I found similar questions, but it is a seed problem, and I don't think it can fit my problem cause I'm not setting seed.
$$anonymous$$ake sure that you fill the items array properly. Try this:
void Awake()
{
Instantiate (items[Random.Range(0, 2)], new Vector3(0,0,0), Quaternion.identity);
}
Or this:
int X;
void Awake()
{
X = Random.Range(0, 2);
Instantiate (items[X], new Vector3(0,0,0), Quaternion.identity);
}
I always declare / add the starting value to my variables in the first method, not in the head of the script. I hope it helped, if not let me know.
Answer by zharik86 · Sep 13, 2014 at 10:49 AM
Correct initialization your variable "X". Change code:
public GameObject[] items;
int X = 0;
void Awake() {
X = Random.Range(0,2); //Gets int value from 0 to 1
Instantiate (items[X], new Vector3(0,0,0), Quaternion.identity);
}
I hope that it wil help you.
I dont see the point to answer an answered question :) I guess you didn't see my comment. I wrote the same.
His int is not public. By default variables are private.
@$$anonymous$$rAkro$$anonymous$$enTos Yes, you are right. Variable - private. And we wrote our answers at the same time.
Simultaneous posts happen all the time :)
Upvotes for everybody!
The important thing, which zharik was mostly explicit about, is that you can't "run stuff" during a global declaration. Can only assign constants.
Otherwise, init everything in Start. Why didn't int X=Random...
come up as an error? Beats me. And sometimes, illegal stuff does run, since the compiler-writers were bored.
Answer by kumarc123 · Apr 12, 2015 at 06:31 AM
Hi, as per Unity Random.Range for int, the function works with maxValue exclusive. That is unityMaxValue = yourMaxValue + 1
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to slow down random enemy spawn? 1 Answer
I can't get Unity to recognise Random.Range C# 1 Answer
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer