~ Error Cannot implicitly convert type float' to
int’
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Material[] materials;
public float changeInterval = 0.33F;
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
rend.enabled = true;
}
void Update() {
if (materials.Length == 0)
return;
int index = Time.time / changeInterval;
index = index % materials.Length;
rend.sharedMaterial = materials[index];
}
}
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Renderer rend;
void Start ()
{
rend = GetComponent<Renderer> ();
rend.enabled = true;
}
void Update ()
{
int seconds = Time.time;
bool oddeven = seconds % 2 == 0;
rend.enabled = oddeven;
}
}
Playing around with the tutorials and API’s.
Both API examples give same error in 5.01
Time.time is a float, you’ve declared ‘seconds’ as an int, which do not have an implicit conversion, as the error states.
You, my friend, need to learn about data types and casting
I didn’t declare anything; these are both copy paste direct from UNITY’s API pages.
The variable index was declared as int and “time.time / changeInterval” returns a float value.
Convert the value to integer using:
Mathf.FloorToInt
or
Mathf.RoundToInt
Try this:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Material[] materials;
public float changeInterval = 0.33F;
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
rend.enabled = true;
}
void Update() {
if (materials.Length == 0)
return;
int index = Mathf.RoundToInt(Time.time / changeInterval);
index = index % materials.Length;
rend.sharedMaterial = materials[index];
}
}
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Renderer rend;
void Start ()
{
rend = GetComponent<Renderer> ();
rend.enabled = true;
}
void Update ()
{
int seconds = Mathf.RoundToInt(Time.time);
bool oddeven = seconds % 2 == 0;
rend.enabled = oddeven;
}
}
[Edited]
Or
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Material[] materials;
public float changeInterval = 0.33F;
public Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
rend.enabled = true;
}
void Update() {
if (materials.Length == 0)
return;
float index = Time.time / changeInterval;
index = index % materials.Length;
rend.sharedMaterial = materials[Mathf.FloorToInt(index)];
}
}
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Renderer rend;
void Start ()
{
rend = GetComponent<Renderer> ();
rend.enabled = true;
}
void Update ()
{
float seconds = Time.time;
bool oddeven = seconds % 2 == 0;
rend.enabled = oddeven;
}
}
Denis Lemos
I think people are missing the OP’s point, which is that the Unity scripting reference examples contain the errors.
1 Like