首页 > 解决方案 > 如何使用一个 Input.GetKeyDown(KeyCode.S) 在多种材质之间切换?

问题描述

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

public class SkyBox : MonoBehaviour
{
    public Material[] skyboxes;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.S))
        {
            for (int i = 0; i < skyboxes.Length; i++)
            {
                RenderSettings.skybox = !skyboxes[i];
            }
        }
    }
}

首先不确定使用循环是否是个好主意。

第二个在右侧出现错误:

!skyboxes[i]

无法将类型“bool”隐式转换为“UnityEngine.Material”

标签: c#unity3d

解决方案


这是一个有效的解决方案:

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

public class SkyBox : MonoBehaviour
{
    public Material[] skyboxes;

    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            index++;
            if (index == skyboxes.Length)
                index = 0;
            RenderSettings.skybox = skyboxes[index];
        }
    }
}

推荐阅读