- Home /
Question by
guccipf · Aug 11, 2019 at 08:56 PM ·
c#background
How Can I Randomize My Camera Color Every One Second Using a Script?
Hey guys im trying to make a game where the background should change every 1 sec with one of the 4 colors i choose this is the code im using im a beginer on making games so pls tell me where is the issue :
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class camera_movements : MonoBehaviour {
public Camera cam;
public float time;
void FixedUpdate()
{
Invoke("changecolor", time);
}
private void changecolor()
{
float randomnum = Random.Range(1f, 5f);
if (randomnum == 1f)
{
cam.backgroundColor = new Color(255f, 0f, 0f, 255f);
}
else if (randomnum == 2f)
{
cam.backgroundColor = new Color(0f, 255f, 0f, 255f);
}
else if (randomnum == 3f)
{
cam.backgroundColor = new Color(0f, 0f, 255f, 255f);
}
else if (randomnum == 4f)
{
cam.backgroundColor = new Color(255f, 0f, 255f, 255f);
}
}
}
Comment
Best Answer
Answer by Hellium · Aug 11, 2019 at 08:58 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera_movements : MonoBehaviour
{
public Camera cam;
public Color[] backgroundColors = new Color[]
{
new Color(1, 0, 0, 1),
new Color(0, 1, 0, 1),
new Color(0, 0, 1, 1),
new Color(1, 0, 1, 1)
};
public float delay;
private float timer;
void Update()
{
timer += Time.deltaTime;
if( timer > delay )
{
timer -= delay ;
ChangeBackgroundColor();
}
}
private void ChangeBackgroundColor()
{
cam.backgroundColor = backgroundColors[ Random.Range(0, backgroundColors.Length) ];
}
}
With coroutines:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class camera_movements : MonoBehaviour
{
public Camera cam;
public Color[] backgroundColors = new Color[]
{
new Color(1, 0, 0, 1),
new Color(0, 1, 0, 1),
new Color(0, 0, 1, 1),
new Color(1, 0, 1, 1)
};
public float delay;
void Start()
{
StartCoroutine( ChangeBackgroundColor() );
}
private IEnumerator ChangeBackgroundColor()
{
WaitForSeconds wait = new WaitForSeconds(delay);
while( true )
{
yield return wait;
cam.backgroundColor = backgroundColors[ Random.Range(0, backgroundColors.Length) ];
}
}
}