Unity与C#入门遇报错:Assets/TextChangeScript.cs(14,29)意外符号错误
解决Unity C#中的CS1525错误及协程使用问题
嘿,作为Unity新手遇到这种语法错误很正常,我来帮你拆解问题并搞定它!
错误原因分析
你碰到的Assets/TextChangeScript.cs(14,29): error CS1525: Unexpected symbol (', expecting ,', ;', or ='错误,根源在这行代码:
yield WaitForSeconds (3);
具体有两个核心问题:
- 协程方法返回类型不对:
Start方法默认是void类型,但如果要使用yield实现延迟逻辑,必须把返回类型改成IEnumerator——这是Unity协程的硬性要求。 - yield语法写错了:正确的协程延迟写法应该是
yield return new WaitForSeconds(3);,你既漏了return关键字,也没有用new来实例化WaitForSeconds对象。
修正后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextChangeScript : MonoBehaviour { public Text m_MyText; public Text OtherText; // 把返回类型从void改成IEnumerator IEnumerator Start() { m_MyText.text = "There was once a mother and her child"; // 修正yield语法,正确创建延迟对象 yield return new WaitForSeconds(3); m_MyText.text = "The mother loved her child very dearly"; } }
额外可选方案
如果你觉得协程写法有点绕,也可以用Invoke方法实现延迟,这种写法不需要修改Start的返回类型,适合简单的延迟场景:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextChangeScript : MonoBehaviour { public Text m_MyText; public Text OtherText; void Start() { m_MyText.text = "There was once a mother and her child"; // 3秒后调用ChangeText方法 Invoke(nameof(ChangeText), 3); } void ChangeText() { m_MyText.text = "The mother loved her child very dearly"; } }
内容的提问来源于stack exchange,提问作者mohammed
相关产品推荐
相关产品推荐

