Unity3D How To Change Skybox With Script

Unity3D How To Change Skybox With Script 

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.

Create a public material, save the script to a GameObject, and then drag/drop the skybox material in your Inspector.

Further down in your Start or a function that you call in your code, make the change:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeSkybox : MonoBehaviour {

 public Material skybox1;

 // Use this for initialization
 void Start () {
    RenderSettings.skybox = skybox1;
 }
 
 // Update is called once per frame
 void Update () { 
 }
}

That is it. Next I’ll add a few changes to choose a random skybox each time. Using the following code, you will need to select the script or GameObject with the script attached and look for the “skyboxes” array in the Inspector. Click the arrow to expand it and change the 0 to however many skybox materials you have. Now you’ll have a few fields to drag/drop your skybox materials. The following script will choose one randomly at start up. To make the random change again, simply call the function ChangeMySkybox();

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeSkybox : MonoBehaviour {

public Material[] skyboxes;

// Use this for initialization
 void Start () {
    ChangeMySkybox();
 }
 
 // Update is called once per frame
 void Update () { 
 }

void ChangeMySkybox()
 {
    int x = Random.Range(0, skyboxes.Length - 1);
    RenderSettings.skybox = skyboxes[x];
 }
}


Unity3D How To Change Skybox With Script