用c#写一个进入场景后,场景中的图片“一”渐隐渐现,一秒后平滑显示图片“三”渐隐渐现的代码
时间: 2023-10-15 09:02:04 浏览: 37
以下是用C#实现进入场景后,图片“一”渐隐渐现,一秒后平滑显示图片“三”渐隐渐现的代码:
```csharp
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class SceneController : MonoBehaviour
{
public Image image1;
public Image image2;
public Image image3;
void Start()
{
StartCoroutine(FadeImage(image1, 0f, 1f, 2f)); // 图片“一”渐隐渐现
StartCoroutine(ShowImage3()); // 一秒后平滑显示图片“三”渐隐渐现
}
IEnumerator FadeImage(Image image, float startAlpha, float endAlpha, float duration)
{
Color color = image.color;
color.a = startAlpha;
image.color = color;
float startTime = Time.time;
float endTime = startTime + duration;
while (Time.time < endTime)
{
float progress = (Time.time - startTime) / duration;
color.a = Mathf.Lerp(startAlpha, endAlpha, progress);
image.color = color;
yield return null;
}
color.a = endAlpha;
image.color = color;
}
IEnumerator ShowImage3()
{
yield return new WaitForSeconds(1f); // 等待一秒
StartCoroutine(FadeImage(image2, 1f, 0f, 2f)); // 图片“二”渐隐
StartCoroutine(FadeImage(image3, 0f, 1f, 2f)); // 图片“三”渐隐渐现
}
}
```
在代码中,我们定义了三个Image对象:image1、image2和image3。在Start方法中使用了两个协程:FadeImage和ShowImage3。
FadeImage方法实现了图片渐隐渐现的效果,接受四个参数:Image对象、起始透明度、结束透明度和持续时间。它使用while循环和Mathf.Lerp方法实现了透明度从起始值到结束值的平滑过渡。
ShowImage3方法使用了WaitForSeconds方法等待一秒,然后分别调用FadeImage方法实现了图片“二”渐隐和图片“三”渐隐渐现的效果。
希望这个代码对您有所帮助!
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)