Search code examples
c#arraysunity-game-engineskybox

Unity - Get random Skybox out of array


For a school task I have to make a basic video game. I am trying to make a basic version of a space game.

I want an array with multiple skyboxes in it and, when launching the game, I want the game to choose a random Skybox out of the array. That way you will have the feeling that you are in a different spawnlocation everytime.

Can anyone help me? I have been looking on google but I cannot find anything helpful.

The skyboxes are located in a folder named:

  • 'Assets/SkyBox Volume 2/DeepSpaceBlue' file name = DSB
  • 'Assets/SkyBox Volume 2/DeepSpaceGreen' file name = DSG
  • ...

This is my current code and it contains errors.

EDIT

using UnityEngine;
using System.Collections;
public class RandomSkybox : MonoBehaviour
{
    public Material[] materials;

    // Use this for initialization
    void Start()
    {
        skyBoxMaterial = materials[Random.Range(0, materials.length)];
        RenderSettings.skybox = skyBoxMaterial;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Errors:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0103  The name 'skyBoxMaterial' does not exist in the current context SpaceRaiders.CSharp D:\Documenten\Unity\SpaceRaiders\Assets\Scripts\Space\RandomSkybox.cs   10  Active
Error   CS1061  'Material[]' does not contain a definition for 'length' and no extension method 'length' accepting a first argument of type 'Material[]' could be found (are you missing a using directive or an assembly reference?)   SpaceRaiders.CSharp D:\Documenten\Unity\SpaceRaiders\Assets\Scripts\Space\RandomSkybox.cs   10  Active
Error   CS0103  The name 'skyBoxMaterial' does not exist in the current context SpaceRaiders.CSharp D:\Documenten\Unity\SpaceRaiders\Assets\Scripts\Space\RandomSkybox.cs   11  Active

Solution

  • public Skybox[] skyBoxes;
    

    you have to

    drag the items to the array

    it's that simple. In the Inspector, set the length to say "5", and then drag your five items in. Nothing more to it.


    Also in the latest version you have posted,

    skyBoxMaterial = materials[Random.Range(0, materials.length)];
    

    You forgot to declare the variable. it's that simple.

    Material skyBoxMaterial;
    skyBoxMaterial = materials[Random.Range(0, materials.length)];
    

    for "length" obviously it "Length". Don't forget for List<> it is .Count not .Length.