Unity代码设置天空盒子skybox 及定时切换


前言:并非自创,看的是同行的博文——在此向前人致谢

一、代码

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

public class ChangeSkyBox : MonoBehaviour
{
    
    
    public Material[] mats;
    private int index=0;
    public int changeTime;//更换天空盒子的秒数
    // Start is called before the first frame update
    void Start()
    {
    
    
        Debug.Log(System.DateTime.Now.Hour);
        InvokeRepeating("ChangeBox",0,changeTime);
    }

    // Update is called once per frame
    void Update()
    {
    
    
        
        //if(System.DateTime.Now.Hour>6&& System.DateTime.Now.Hour<18)
        //{
    
    
        //    RenderSettings.skybox = mats[0];
        //}
        //else
        //{
    
    
        //    RenderSettings.skybox = mats[1];
        //}
    }
    public void ChangeBox()
    {
    
    
    
        RenderSettings.skybox = mats[index];
        index++;
        index %= mats.Length;
    }
}

二、解析

1、天空盒子 代码设置 函数
RenderSettings.skybox = 天空盒子材质球;

2、切换原理

public void ChangeBox()
    {
    
    
    
        RenderSettings.skybox = mats[index];
        index++;
        index %= mats.Length;
    }

假设有两个天空盒子,放在材质数组中
定义整形变量index,表示要使用材质球的索引
每切换一次索引 index 加1(index++),每次切换要用到的材质球是mats[index]
依次用到的材质球分别是:
mats[0]
mats[1]
mats[2] 2%2=0 即mats[0]
mats[3] 3%2=1 即mats[1]
mats[4] 4%2=0 即mats[0]

3、定时调用
用InvokeRepeating函数,每隔一段时间,调用一下2、的切换函数

 public int changeTime;//更换天空盒子的秒数
  
    void Start()
    {
    
    
        Debug.Log(System.DateTime.Now.Hour);
        InvokeRepeating("ChangeBox",0,changeTime);
    }

三、核心

循环算法:
索引加出“数组范围”时,整除“数组长度”,会重新循环——如:索引范围0、1,
当索引加成2时,出了数组范围,整除“数组长度”,得到0,开始循环。

猜你喜欢

转载自blog.csdn.net/weixin_42935398/article/details/124449162