untiy学习——开启协程

本文介绍如何在Unity3D中利用StartCoroutine方法和Fade协程实现游戏物体随时间逐渐变为透明的效果,并展示了如何使用WaitForSeconds类为这一过程添加延迟。

继上一篇,我们要调用Fade方法,我们就要使用unity3D中的StartCoroutine方法。
下面我们就通过StartCoroutine方法来开启定义协程Fade,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CoroutineTest : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.LeftArrow))
            StartCoroutine("Fade");
    }
    IEnumerator Fade()
    {
        for (float f = 1f; f >= 0; f -= 0.1f)
        {
            Color c = GetComponent<Renderer>().material.color;
            //Color c = renderer.material.color;
            c.a = f;
            GetComponent<Renderer>().material.color = c;
            yield return null;

        }
    }
}

将该脚本挂载在某个游戏对象上,开始运行游戏,在游戏运行期间按下键盘方向左键便开启了一个协程Fade,也就实现了游戏对象随着时间而逐渐变得透明的功能。
这里写图片描述
注:
在场景中创建一个cube并且拖入材质,拖入以上脚本,画红线的地方是我自己选择的,运行场景。这里写图片描述
注:这就是最终结果。

但是执行过脚本之后你会发现一个问题,那就是协程是每帧都会恢复执行的,如果想要一个延时的效果,经过一段时间之后再恢复执行是否有可能呢?答案是可以的。这里又会引入一个新的类WaitForSeconds。通过它可以实现延时恢复执行逻辑的需求。
我们现在做一个使用WaitForSeconds类的实例:

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

public class ExampleClass : MonoBehaviour {

    // Use this for initialization
    void Start () {
        StartCoroutine("Example");
    }
    IEnumerator Example()
    {
        print(Time.time );
        yield return new WaitForSeconds(5);
        print(Time.time);
    }
    // Update is called once per frame
    void Update () {

    }
}

将这个脚本挂在场景内摄像机上,然后运行游戏,可以在unity3D的输出窗口看到打印出的语句。
这里写图片描述
注:看到使用WaitForSeconds使协程Example推迟了5秒才恢复执行之后的逻辑。

接下来我们要做的是使用WaitForSeconds来延缓游戏物体变得透明。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CoroutineTest : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.LeftArrow))
            StartCoroutine("Fade");
    }
    IEnumerator Fade()
    {
        for (float f = 1f; f >= 0; f -= 0.1f)
        {
            Color c = GetComponent<Renderer>().material.color;
            //Color c = renderer.material.color;
            c.a = f;
            GetComponent<Renderer>().material.color = c;
            yield return new WaitForSeconds(.5f);

        }
    }
}

效果图:
这里写图片描述
这里写图片描述

<think>我们正在讨论Unity中的协程打字效果。用户要求一个示例。 我们将创建一个简单的脚本,使用协程逐个显示文本字符,实现打字效果。 步骤: 1. 创建一个C#脚本,比如TypewriterEffect。 2. 在脚本中,我们将使用协程来逐个字符地显示文本。 3. 我们需要一个公共字段来设置每个字符显示的延迟时间。 4. 我们可以将脚本附加到带有Text组件的GameObject上(对于旧版UI)或者TextMeshPro组件(更常用)。 注意:这里假设用户使用的是Unity的UGUI(Text)或TextMeshPro。由于问题中没有指定,我们将提供一个同时适用于旧版Text和TextMeshPro的通用方法(通过判断使用哪个组件)。 但是,为了简单起见,我们可以先提供一个使用UnityEngine.UI.Text的版本,然后如果需要,再提供TextMeshPro的版本。 由于用户要求的是示例,我们先提供一个基础的。 我们将创建一个协程函数,该函数逐个字符地追加到文本字符串中,并等待一段时间。 代码示例:</think>在 Unity 中实现协程打字效果是一种常见的文本动画技术,下面是完整实现方法和示例代码: ### 实现原理 打字效果的核心是通过协程(Coroutine)逐字符显示文本: 1. 将目标文本分解为字符数组 2. 使用 `yield return new WaitForSeconds()` 控制字符显示间隔 3. 通过字符串拼接逐步构建显示文本 ### 完整实现代码 ```csharp using UnityEngine; using UnityEngine.UI; using System.Collections; public class TypewriterEffect : MonoBehaviour { [SerializeField] private float charDelay = 0.1f; // 字符显示间隔(秒) [SerializeField] private bool autoStart = true; // 是否自动开始 private string fullText; // 完整文本 private Text textComponent; // UI文本组件 void Start() { textComponent = GetComponent<Text>(); fullText = textComponent.text; // 保存初始文本 textComponent.text = ""; // 清空显示 if(autoStart) StartCoroutine(TypeText()); } // 打字机协程 IEnumerator TypeText() { foreach(char c in fullText) { textComponent.text += c; // 追加字符 yield return new WaitForSeconds(charDelay); } } // 外部调用接口 public void StartTyping(string newText = null) { if(!string.IsNullOrEmpty(newText)) fullText = newText; StopAllCoroutines(); textComponent.text = ""; StartCoroutine(TypeText()); } } ``` ### 使用步骤 1. **创建UI文本**: - 菜单栏选择 `GameObject > UI > Text` - 调整文本框大小和字体样式 2. **挂载脚本**: - 将脚本拖拽到Text游戏对象上 - 在Inspector中调整参数: - `Char Delay`:字符显示间隔(推荐0.05-0.2秒) - `Auto Start`:是否自动开始打字效果 3. **自定义控制**(可选): ```csharp // 在其他脚本中控制打字机 public TypewriterEffect typewriter; void StartDialogue() { typewriter.StartTyping("新的文本内容..."); } ``` ### 高级优化技巧 1. **支持TextMeshPro**: ```csharp // 替换Text为TextMeshProUGUI using TMPro; private TextMeshProUGUI textComponent; void Start() { textComponent = GetComponent<TextMeshProUGUI>(); // 其余代码相同... } ``` 2. **添加音效反馈**: ```csharp [SerializeField] private AudioClip typeSound; private AudioSource audioSource; void Start() { audioSource = GetComponent<AudioSource>(); } IEnumerator TypeText() { foreach(char c in fullText) { textComponent.text += c; audioSource.PlayOneShot(typeSound); // 播放打字音效 yield return new WaitForSeconds(charDelay); } } ``` 3. **支持富文本标记**(避免解析标签): ```csharp IEnumerator TypeText() { string tempText = ""; bool inTag = false; foreach(char c in fullText) { if(c == '<') inTag = true; if(c == '>') inTag = false; tempText += c; textComponent.text = tempText + (inTag ? "" : "<color=#00000000>" + fullText.Substring(tempText.Length) + "</color>"); yield return new WaitForSeconds(inTag ? 0 : charDelay); } } ``` ### 常见问题解决 1. **文本闪烁问题**: - 确保Canvas的渲染模式为 `Screen Space - Overlay` 或 `Camera` - 在Canvas组件上启用 `Pixel Perfect` 设置 2. **协程不启动**: - 检查游戏对象是否激活 - 确保没有在其他地方调用 `StopAllCoroutines()` - 通过 `StartCoroutine("TypeText")` 启动时检查拼写错误 3. **性能优化**: - 长文本使用 `StringBuilder` 代替字符串拼接 - 超过500字符时考虑分页显示 > 协程打字效果是Unity对话系统的核心实现技术之一,广泛应用于RPG游戏的对话系统和UI交互动画中[^1]。通过调整字符间隔和添加音效,可以显著增强用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值