-2

im trying to make a code that grabs a random number, then takes that number and puts it into a sleep/count down timer, but everytime i try to run the code in unity it tells me i cant convert a float to an int at line 14,39. can someone help me with this? i tried making it grab a randomized number and use that number for a sleep/countdown (not an on-screen count down)

heres my code:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomTimer : MonoBehaviour { public float RadNum = 0f; void Start() { RadNum = Random.Range(1000, 20000); Debug.Log(RadNum); System.Threading.Thread.Sleep(RadNum); } } 
2

2 Answers 2

-1

Avoid it completely! You are using the wrong method. For Int, use .Next instead of .Range

Random.Next

Random r = new Random(); int rInt = r.Next(1000, 20000); 
Sign up to request clarification or add additional context in comments.

Comments

-2

Did you try casting?

RadNum = Random.Range(1000, 20000); int x = (int) RadNum; 

Of course an int can't represent the exact float value. A 42.2 will be a 42 only and so on.

3 Comments

Better to use Round first if you are casting
@ChrisSchaller I don't think this is important for a random number.
Do not get into the habit of ignoring bad code because it's just a random number If you want int, use Next that gives you ints, explicit casts are red flags on their own. they are an indication that you are doing something unexpected and you might not know why.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.