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

Unity C#未调用方法却自动执行的问题排查求助

问题解决:Unity中未调用方法自动执行、逻辑异常问题

问题描述

我是Unity与C#新手,目前遇到代码未调用的方法自动执行的问题,打乱了游戏逻辑,找不到解决办法。具体情况:

  • 界面显示“Day 2 - At Sea”时,dayLoop()方法自动运行(通过Debug.Log确认),运行后还触发自定义的start()方法(从start()内的Debug.Log打印出新的shipCondition可得知);
  • dayLoop()内的Debug.Log大量输出,但未执行其中if语句内的逻辑。

相关代码(修正语法错误后)

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

public class ShipGame : MonoBehaviour // 补上必要的MonoBehaviour继承
{
    public TextMeshProUGUI mainText;
    public TextMeshProUGUI titleText;
    public Button b1;
    public Button b2;
    public Button b3;
    public Button b4;
    public Button b5;
    public TextMeshProUGUI b1Text;
    public TextMeshProUGUI b2Text;
    public TextMeshProUGUI b3Text;
    public TextMeshProUGUI b4Text;
    public TextMeshProUGUI b5Text;
    public Image shipSketch1; // 补上未定义的变量
    StringBuilder t = new StringBuilder();
    StringBuilder tt = new StringBuilder();
    
    // 游戏变量
    bool delays;
    bool dead;
    List<string> weather = new List<string>{"sunny", "rain", "storm", "lightning storm", "dry lightning"};
    string weatherPro;
    string dayWeather;
    bool badWeather;
    List<string> capRes = new List<string>{"responsible", "not responsible", "very responsible"};
    string captainResponsibility;
    List<string> shipCon = new List<string>{"great", "great", "great", "great", "shipworms", "bad patch"}; // 修正拼写错误"geat"
    string shipCondition;
    bool badPatchDiscovered;
    bool shipwormsDiscovered;
    List<string> ranBool = new List<string>{"yes", "no"};
    List<string> deathTime = new List<string>{"yes", "no", "no", "no", "no"};
    System.Random rng; // 全局随机数生成器

    void Update()
    {
        mainText.text = t.ToString();
        titleText.text = tt.ToString();
    }

    void end()
    {
        clear();
        addTitle("The End");
        b3Text.text = "Play Again";
        b3.onClick.AddListener(GameStart); // 绑定正确的重启方法
    }

    string random(List<string> L)
    {
        int index = rng.Next(L.Count);
        string randomString = L[index];
        return randomString;
    }

    void allButtonsGone()
    {
        b1.gameObject.SetActive(false);
        b2.gameObject.SetActive(false);
        b3.gameObject.SetActive(false);
        b4.gameObject.SetActive(false);
        b5.gameObject.SetActive(false);
    }

    void allImagesGone()
    {
        shipSketch1.gameObject.SetActive(false);
    }

    void newLine(){add(Environment.NewLine);}
    void add(string words){t.Append(words);}
    void addTitle(string words){clear(); tt.Append(words); b3.gameObject.SetActive(true); b3Text.text = "Go";}
    void clear()
    {
        t.Clear();
        tt.Clear(); 
        allImagesGone(); 
        allButtonsGone();
        // 清空所有按钮的旧监听,避免累积触发
        b1.onClick.RemoveAllListeners();
        b2.onClick.RemoveAllListeners();
        b3.onClick.RemoveAllListeners();
        b4.onClick.RemoveAllListeners();
        b5.onClick.RemoveAllListeners();
    }
    void showImage(Image img){img.gameObject.SetActive(true);}
    void button(Button b, TextMeshProUGUI bt, String words){b.gameObject.SetActive(true); bt.text = words;}

    // 重命名自定义方法,避免和Unity生命周期方法Start混淆
    void GameStart()
    {
        clear();
        badWeather = false;
        dead = false;
        delays = false;
        badPatchDiscovered = false;
        shipwormsDiscovered = false;
        rng = new System.Random(); // 只初始化一次随机数生成器
        shipCondition = random(shipCon);
        Debug.Log(shipCondition);
        intro();
    }

    // 修正dayLoop的语法错误
    void dayLoop()
    {
        clear();
        button(b3, b3Text, "Next");
        if(dead == true){return;}
        dayWeather = random(weather);
        Debug.Log("当前天气:" + dayWeather); // 日志确认变量值
        // 示例天气逻辑
        if(dayWeather == "storm"){
            add("海上刮起了强烈风暴,船身开始摇晃!");
            newLine();
            badWeather = true;
        }
        // 示例船况逻辑
        if(shipCondition == "shipworms" && !shipwormsDiscovered){
            add("船员发现船身附着大量船蛆,船身结构受损!");
            newLine();
            shipwormsDiscovered = true;
        }
    }

    void dayLoop1(){dayLoop(); b3.onClick.AddListener(wifeDay1);}
    void dayLoop2(){dayLoop(); b3.onClick.AddListener(wifeDay2);}

    void day1()
    {
        clear();
        addTitle("Day 1 - At Sea");
        b3.onClick.AddListener(dayLoop1);
    }

    void day2()
    {
        clear();
        addTitle("Day 2 - At Sea");
        b3.onClick.AddListener(dayLoop2);
    }

    // 补充缺失的占位方法
    void intro(){}
    void wifeDay1(){}
    void wifeDay2(){}
}

关键修复点

  1. 按钮事件累积导致自动触发:
    在clear()方法中添加RemoveAllListeners(),每次切换场景时清空所有按钮的旧监听,避免之前绑定的事件被重复触发。

  2. 方法名混淆触发错误逻辑:
    把自定义的start()重命名为GameStart(),避免和Unity内置的生命周期方法Start()(大写S)混淆;同时修正end()中绑定的方法名,确保点击“Play Again”时调用正确的重启方法。

  3. 语法错误导致逻辑异常:
    修正dayLoop方法的定义(添加()),补上缺失的变量定义(如shipSketch1),修正shipCon列表中的拼写错误。

  4. 随机数生成器重复创建导致结果异常:
    将System.Random改为类成员变量,只在启动时初始化一次,避免短时间内多次调用生成相同随机数。

  5. 确保if逻辑可执行:
    在dayLoop()中添加日志输出确认dayWeather和shipCondition的实际值,补充示例if逻辑,确保代码分支能正常触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:04:53