- Home /
Calling 2 specific random float numbers in random.range using array not working!
I want my object to instantiate at two specific locations. No in between. But I'm getting an error that it cannot convert type float to int implicitly. Help! Here's my code. Thank You.
public class ObjSpawner : MonoBehaviour {
public GameObject Obj;
float[] randompos = new float[] {1f, -0.0254777070063694f};
// this big number is a properly calculated number.
void Start () {
StartObjSpawn ();
}
void Update ()
}
public void StartObjSpawn(){
StartCoroutine("SpawnObj");
}
public void StopObjSpawn() {
StopCoroutine("SpawnObj");
}
IEnumerator SpawnObj()
{
Instantiate(Obj, new Vector3(transform.position.x,transform.position.y)*(randompos[Random.Range(1f,randompos.Length)]), Quaternion.identity);
yield return new WaitForSeconds(Random.Range(1.5f, 2f));
StartCoroutine("SpawnObj");
}
}
Change to
Instantiate(Obj, new Vector3(transform.position.x,transform.position.y)*(randompos[Random.Range(1, randompos.Length)]), Quaternion.identity);
yield return new WaitForSeconds(Random.Range(1, 2));
Random.Range(int, int) requires you to pass integers as its arguments. It then returns a random integer between your first argument (the lower bound) and the upper bound $$anonymous$$us 1.
You are giving it floats, and it is telling you that it will not convert them automatically into integers for you.
Answer by Legend_Bacon · Oct 30, 2017 at 07:36 PM
Hello there,
As the first argument of your Random.Range() call, you are using 1f, which is a float. What you probably meant to do is (randompos[Random.Range(0, randompos.Length)])
, which would give you either 0 or 1, which would correspond to either 1f or -0.0254777070063694f.
Let us know if that fixes it! Best of luck,.
~LegendBacon
Answer by pako · Oct 30, 2017 at 07:57 PM
You're getting the error because randompos.Length
returns an integer, and you're using it in Random.Range
with the first argument as a float.
Since you want to use the result of Random.Range
as the index of an element in randompos
array, you should provide two integers in Random.Range
. And since the first element of the array is indexed as 0 that's what you should use for the first integer.
So use:
Instantiate(Obj, new Vector3(transform.position.x,transform.position.y)*(randompos[Random.Range(0,randompos.Length)]), Quaternion.identity);
Thank you for explaining why it went wrong! It's working now!