using UnityEngine;
using System.Collections;
public class BackgroundController : MonoBehaviour {
public Material m;
public Material level2;
public Material level3;
public Material level4;
public Material funny;
public Material fin;
void Update ()
{
renderer.material = level2;
/*if(Time.time == 40)
{
renderer.material = level3;
}
if(Time.time == 60)
{
renderer.material = level4;
}
if(Time.time == 80)
{
renderer.material = funny;
}
if(Time.time == 83)
{
renderer.material = fin;
}*/
}
}
Time.time is a floating point value and rarely lands on a round integer number. Typically you want to use comparisons that use a range of values instead of equality when working with floating point numbers. So you have a few choices to fix this code. First you could use integer comparison and just round Time.time. For example, each comparison would be:
if (Mathf.RoundToInt(Time.time) == 40)
Note that the material will get repeatedly set as long as Time.time is forty-something.
Or you could restructure your code to use range comparison:
using UnityEngine;
using System.Collections;
public class BackgroundController : MonoBehaviour {
public Material m;
public Material level2;
public Material level3;
public Material level4;
public Material funny;
public Material fin;
void Update ()
{
if(Time.time >= 83)
{
renderer.material = fin;
}
else if(Time.time >= 80)
{
renderer.material = funny;
}
else if(Time.time >= 60)
{
renderer.material = level4;
}
else if(Time.time >= 40)
{
renderer.material = level3;
}
else {
renderer.material = level2;
}
}
}
Note that the material will get reset at each frame with this solution. You could code around this by saving the current material and only resetting if there is a change.
Or you can move to an integer based solution that counts seconds. InvokeRepeating() is used to make ‘SetMaterial()’ be called once per second. Now the material will only be set at the specific thresholds.
using UnityEngine;
using System.Collections;
public class BackgroundController : MonoBehaviour {
public Material m;
public Material level2;
public Material level3;
public Material level4;
public Material funny;
public Material fin;
int seconds = 0;
void Start() {
renderer.material = level2;
InvokeRepeating("Seconds", 0.0f, 1.0f);
}
void SetMaterial ()
{
seconds++;
if(seconds == 40)
{
renderer.material = level3;
}
if(seconds == 60)
{
renderer.material = level4;
}
if(seconds == 80)
{
renderer.material = funny;
}
if(seconds == 83)
{
renderer.material = fin;
}
}
}