- Home /
Random.Range not working, no errors given c#
I want, at the beginning of the scene, for my object to appear at a random x value within a range. This is my simple code, and it's not working and I don't have an error... I know what I did wrong must be something simple, can I get some help?
using UnityEngine; using System.Collections;
public class Upward : MonoBehaviour {
Vector3 velocity = Vector3.zero;
public Vector3 AntiGravity;
// Use this for initialization
void Start () {
int RandomInt = (int)Random.Range(-0.755f, 0.755f);
transform.position = new Vector3 (RandomInt, -3.4f, -1.5f);
}
// Update is called once per frame
void Update () {
if (transform.position.y <= 3.35) {
velocity -= AntiGravity * Time.deltaTime;
transform.position -= velocity * Time.deltaTime;
}
}
}
Answer by tanoshimi · Jul 15, 2015 at 06:24 AM
int RandomInt = (int)Random.Range(-0.755f, 0.755f);
This is always going to be 0. Why are you creating an int? Positions are floating point vectors, so if you want a y value between -0.755 and 0.755:
float RandomInt = Random.Range(-0.755f, 0.755f);
Exactly. You're casting a float (the output from the Random.Range function.) to an int. That usually results in ditching the numbers behind the dot and leaving just an int.
You have to decide whether you want integer or floating point numbers and use the correct overload of the Random.Range function.