Unity C# 答题游戏:修改错误次数触发返回分类逻辑求助
Hey there! Since you're new to programming, I'll walk you through exactly how to adjust your script so users get two wrong attempts before being sent back to the category page. Let's break this down simply.
Core Idea
We just need to add a counter to track how many times the user clicks a wrong option, then only trigger the return to the category page once that counter hits 2.
Step-by-Step Implementation
1. Add a Wrong Attempt Counter
First, add a private variable to your quiz script to keep track of wrong clicks. This variable will stay active while the user is in the quiz session:
private int wrongAttempts = 0;
2. Update the Wrong Option Click Logic
Find the method that handles when a user clicks a wrong option (it might be tied to your button's OnClick event, or named something like OnWrongOptionClicked). Modify it to increment the counter and check if we've hit the 2-attempt limit:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; // Include this if you're switching scenes public class QuizHandler : MonoBehaviour { // Track number of wrong attempts private int wrongAttempts = 0; // Link this method to your wrong option buttons in the Inspector public void OnWrongOptionSelected() { // Increase the wrong attempt count by 1 wrongAttempts++; // Check if we've reached 2 wrong attempts if (wrongAttempts >= 2) { // Reset the counter before leaving (so it's fresh for the next quiz session) wrongAttempts = 0; // Replace "CategoryScene" with your actual category page scene name SceneManager.LoadScene("CategoryScene"); } else { // Optional: Give the user feedback (you can replace this with UI text instead of a debug log) Debug.Log($"Oops! That's {wrongAttempts} wrong attempt — one more and you'll go back to categories."); } } // Don't forget to reset the counter when the user gets a question right! public void OnCorrectOptionSelected() { wrongAttempts = 0; // Add your logic for correct answers here (e.g., load the next question) } }
3. Key Things to Remember
- Button Binding: Make sure all your wrong option buttons are set to call
OnWrongOptionSelectedin theirOnClickevent in the Unity Inspector. - Reset the Counter: Always reset
wrongAttemptswhen the user answers correctly or leaves the quiz — otherwise, the count will carry over to the next question or session. - Customize Return Logic: If you're not using
SceneManagerto switch back to categories (e.g., using UI panels instead), replaceSceneManager.LoadScenewith your own code to show the category panel/hide the quiz panel.
内容的提问来源于stack exchange,提问作者John Jose Mergillano

