unity 2d 入门 飞翔小鸟 场景淡入淡出功能(三)

本文介绍了如何在Unity中使用C#编写FadeInOut脚本,控制图片的透明度实现场景的淡入淡出效果,以及如何在GUI上处理场景切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在图层新建个空的图层

在这里插入图片描述
在这里插入图片描述
场景2
在这里插入图片描述

2创建c#脚本

脚本创建好后,将脚本推拽进空白图层里面,将黑色图片拉进去脚本的参数里面,如上面最后一张图,两个切换的场景都要进行上述操作

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

public class FadeInOut : MonoBehaviour
{
    //脚本传进来的图片
    public Texture img;
    //透明度
    public static float alpha = 0;
    //淡出
    public static bool fadeOut = false;
    //淡入
    public static bool fadeIn = false;
    //前端传过来的速度
    public float speed;
    //场景
    private static string scene;

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

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

    //渲染页面调用的得是这个方法
    private void OnGUI()
    {
       // Time.deltaTime 上一帧与当前帧间隔帧数
        if (fadeOut){
            alpha += speed * Time.deltaTime;
            if (alpha>1) {
                fadeOut = false;
                fadeIn = true;
                //场景切换
                SceneManager.LoadScene(scene);
            }
        }
        if (fadeIn) {
            alpha -= speed * Time.deltaTime;
            if (alpha<0) {
                fadeIn = false;
            }
        }
        //调整透明度
        GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,alpha);
       //把场景绘制一张黑色图片
        GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),img);
    }

    public static void SwitchScene(string newScene)
    {
        fadeOut = true;
        scene = newScene;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值