I’m trying to create a simple timer when a boolean equals true but I get an error CS0266
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour {
public float Speed = 5f;
public int invinsibleTimer = 0;
public int invinsibleTime = 5;
Rigidbody2D rb;
public bool invinsible = false;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
}
void Update(){
if (invinsible == true)
{
invinsibleTimer = invinsibleTime + invinsibleTimer;
invinsibleTimer = invinsibleTimer - Time.deltaTime;
if (invinsibleTimer == 0)
{
invinsible = false;
}
}
}
Time.deltaTime is a ‘float’ datatype, which means it can hold decimal fractions. ‘int’ can’t do this, so converting from float to int can cause problems. In this case it’s better to use float everywhere.
using UnityEngine;
using System.Collections;
public class Controller : MonoBehaviour {
public float Speed = 5f;
public float invinsibleTimer = 0; // i changed int to float
public float invinsibleTime = 5;
Rigidbody2D rb;
public bool invinsible = false;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
}
void Update(){
if (invinsible == true)
{
if(invisibleTimer<= 0){
invisibleTimer = invisibleTime; // in your code this would be done every frame
}
invinsibleTimer = invinsibleTimer - Time.deltaTime;
if (invinsibleTimer <= 0) // subtraction might cause this number will be less than zero
{
invinsible = false;
}
}
}
You declare invinsibleTimer as an int on line 8:
public int invinsibleTimer = 0;
But then on line 24, you’re trying to subtract Time.deltaTime, which is a float:
invinsibleTimer = invinsibleTimer - Time.deltaTime;
(Note that if you looked at the line numbers in the error message, you’d have been pointed to this error straight away)