You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中CipherClickHandler脚本index值无法按预期递增问题排查

问题根源

你遇到的问题核心是每个可点击对象都独立挂载了CipherClickHandler脚本,这意味着每个对象都拥有自己的index、counter等成员变量。当你点击第一个对象时,它的index会从0变为1,但点击第二个对象时,触发的是该对象自身脚本里的index(初始值为0),所以看起来每次点击后index都被重置为0。

解决方案

将共享的状态和逻辑抽离到一个单独的管理器类中,让所有可点击对象共享同一套状态变量。具体步骤如下:

1. 创建谜题管理器类

这个类负责维护全局的点击状态、验证逻辑,所有可点击对象的点击事件都将调用该类的方法:

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

public class CipherPuzzleManager : MonoBehaviour
{
    public static CipherPuzzleManager Instance; // 单例,方便访问

    public Text[] alanlar = new Text[5];
    private string[] clickedWords = new string[5];
    private string[] solution = { "a", "b", "c", "d", "e" };
    private int index = 0;
    private int counter = 0;
    private bool success = false;

    private void Awake()
    {
        // 确保全局只有一个管理器实例
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);
    }

    // 供点击对象调用的方法
    public void HandleObjectClick(GameObject clickedObj)
    {
        if (success) return;

        if (index < 5)
        {
            clickedWords[index] = clickedObj.name;
            clickedObj.SetActive(false);
            alanlar[index].text = clickedWords[index];
            ControlCipher(clickedWords[index]);
            index += 1;
        }
        else
        {
            index = 0;
        }
    }

    private void ControlCipher(string token)
    {
        if (counter < 5)
        {
            // 注意这里要用当前index的前一个值,因为index已经自增了
            if (token == solution[index - 1])
            {
                counter++;
            }
        }
        else
        {
            PuzzleSolved();
            success = true;
        }
    }

    private void PuzzleSolved()
    {
        // 你的谜题完成逻辑
    }

    private IEnumerator CoroutineSuccess()
    {
        // 你的成功动画/后续逻辑
        yield return null;
    }
}

2. 修改原点击处理类

去掉原来的状态变量,点击时直接调用管理器的方法:

using UnityEngine;
using UnityEngine.EventSystems;

public class CipherClickHandler : MonoBehaviour, IPointerClickHandler
{
    public void OnPointerClick(PointerEventData pointerEventData)
    {
        // 调用管理器的处理方法
        CipherPuzzleManager.Instance.HandleObjectClick(this.gameObject);
    }
}

3. 场景设置

  • 创建一个空物体,命名为CipherPuzzleManager,将CipherPuzzleManager脚本挂载到该物体上,并在Inspector中赋值alanlar数组。
  • 将修改后的CipherClickHandler脚本挂载到所有15个可点击对象上。
额外修复点

原代码中ControlCipher方法存在逻辑错误:在调用ControlCipher后才执行index +=1,但方法里使用的是当前的index,这会导致验证时用的是下一个位置的答案。在管理器类中已经修正为使用index -1来匹配当前点击的位置。

内容的提问来源于stack exchange,提问作者coner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:13:13