Unity跨脚本传递验证码比对时始终判定输入正确问题求助
问题根因
你代码里最核心的错误是Answer脚本中取值的赋值方向写反了:
你在Answer的Start()方法中写的是:
GameObject.Find("RandomAlphanumerical").GetComponent<RandomAlphaNumerical>().question = correctprompt;
这段代码的逻辑是把Answer脚本里默认空值的correctprompt赋值给验证码生成脚本的question变量,直接覆盖了已经生成好的随机验证码,且你自己的correctprompt始终没有拿到正确的验证码值。
另外还有两个隐性问题:
- Unity中脚本的
Start()执行顺序是不确定的,如果Answer的Start()比验证码生成脚本的Start()先执行,就算赋值方向对了也可能拿到空值 - 你用的
Console.WriteLine()在Unity编辑器中不会输出日志,要排查输入值必须用Debug.Log()
修复步骤
- 修正Answer脚本的赋值逻辑,把验证码值取到本地的
correctprompt变量:
// 把原来Start里的赋值代码改成下面的 correctprompt = GameObject.Find("RandomAlphanumerical").GetComponent<RandomAlphaNumerical>().question;
- 调整验证码生成的执行时机,把
RandomAlphaNumerical脚本的Start()方法改成Awake(),Awake()会在所有Start()之前执行,确保取值时验证码已经生成:
// 原来的public void Start()改成 public void Awake() { // 原有生成逻辑不变 }
- 把输入日志输出改成Unity支持的方法,方便排查:
// 把Console.WriteLine(input)改成 Debug.Log("用户输入:" + input + " 正确验证码:" + correctprompt);
- 可选优化:比对时自动去掉用户输入的前后空格,避免误判:
if (input.Trim() == correctprompt)
免手动配置GameObject的实现方案
用单例模式改造验证码生成脚本,不需要每次调用都Find对象,也不会因为对象名写错报错:
改造后的RandomAlphaNumerical代码:
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class RandomAlphaNumerical : MonoBehaviour { public Text StringText; public string question; // 静态单例实例,全局可直接访问 public static RandomAlphaNumerical Instance { get; private set; } public void Awake() { // 单例初始化 Instance = this; char[] letters = "qwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()".ToCharArray(); System.Random r = new System.Random(); string randomString = ""; for (int i = 0; i < 6; i++) { randomString += letters[r.Next(0, 45)].ToString(); } question = randomString; StringText.text = randomString; } }
改造后Answer脚本的Start()可以直接这么写,不需要找GameObject:
public void Start() { correctprompt = RandomAlphaNumerical.Instance.question; }
内容的提问来源于stack exchange,提问作者steelhead
相关产品推荐
相关产品推荐

