I wanted to change the skybox when a certain event happened. In my case, I wanted a new, random skybox each time a new enemy appeared to fight. First, I will show you how to change the skybox. Second, I will show you how to choose a random skybox and use it. Both scripts are stand alone so choose what works best for you.
To change the skybox using a C# script you have to store the skybox material reference in the Inspector and then assign it during runtime.
Assign a skybox material
using UnityEngine;
public class ChangeSkybox : MonoBehaviour {
public Material skybox1;
void Start() {
RenderSettings.skybox = skybox1;
}
}To randomly select a skybox, attach the script below to a GameObject and populate the skyboxes array in the Inspector.
using UnityEngine;
public class ChangeSkybox : MonoBehaviour {
public Material[] skyboxes;
void Start() { ChangeMySkybox(); }
void ChangeMySkybox() {
int x = Random.Range(0, skyboxes.Length);
RenderSettings.skybox = skyboxes[x];
}
}The random selection example adjusts the upper bound to ensure all configured skyboxes can be selected.