Unity - 从阵列中获取随机天空盒

Unity - Get random Skybox out of array

为了一项学校任务,我必须制作一个基本的视频游戏。 我正在尝试制作 space 游戏的基本版本。

我想要一个包含多个天空盒的数组,并且在启动游戏时,我希望游戏从数组中随机选择一个天空盒。这样你就会有每次都在不同出生地点的感觉。

谁能帮帮我?我一直在寻找 google,但找不到任何有用的信息。

天空盒位于名为:

的文件夹中

这是我当前的代码,其中包含错误。

编辑

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()
    {

    }
}

错误:

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
public Skybox[] skyBoxes;

你必须

将项目拖到数组中

就这么简单。在 Inspector 中,将长度设置为“5”,然后将您的五个项目拖入。仅此而已。


也在您发布的最新版本中,

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

您忘记声明变量。就是这么简单。

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

对于“长度”显然是“长度”。不要忘记 List<> 它是 .Count 而不是 .Length.