Reputation: 1
I am trying to make a zombie spawn at a random spawnpoint out of an array of spawnpoints. Using unity game engine it says "cannot implicitly convert type float to int An explicit conversion exists(are you missing a cast?)"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sown : MonoBehaviour
{
System.Random rnd = new System.Random();
public GameObject[] zomz = new GameObject[1];
public Transform[] spawns = new Transform[9];
public GameObject regzom;
int unonumero = 0;
void Start()
{
foreach (GameObject x in zomz)
{
zomz[unonumero] = Instantiate(regzom, spawns[Mathf.Round(Random.Range(0f, 10f))]);
unonumero++;
}
}
void Update()
{
}
}
Upvotes: 0
Views: 1745
Reputation: 556
Mathf.Found
returns a float, proof. That float is then being used as an index for spawns[]. Only ints are allowed for indexing.
void Start()
{
foreach (GameObject x in zomz)
{
zomz[unonumero] = Instantiate(regzom, spawns[(int)Mathf.Round(Random.Range(0f, 10f))]);
unonumero++;
}
}
Edit: Marco Elizondo's answer is better. Use Mathf.RoundToInt instead.
Upvotes: 1
Reputation: 562
You are almost done, the error is trying to say that you are using a float instead of an int.
Array index can only be integers, in your line:
zomz[unonumero] = Instantiate(regzom, spawns[Mathf.Round(Random.Range(0f, 10f))]);
You are using Mathf.Round(Random.Range(0f, 10f))
to get the random and then round it and that is a wise choice, so you have a random float number like 2.4f rounded to 2.0f, the problem is that it still a float, not an integer.
Matfh has a cool Round method that gives you an integer, you can use this Mathf.RoundToInt()
, like:
zomz[unonumero] = Instantiate(regzom, spawns[Mathf.RoundToInt(Random.Range(0f, 10f))]);
I hope its clear :)
Upvotes: 2