Unity按键按压速率计算功能异常求助:数组元素值重复
Fixing Identical Array Values in Your Unity Press Rate Game
Hey there! Let's figure out why your rate_nums array is ending up with duplicate values and get that press rate calculation working as expected.
Common Culprits for Duplicate Array Values
From your description, the most likely issues are related to timing of data storage or index management in your array. Here are the typical mistakes:
- You’re storing the same cumulative press count instead of per-cycle counts
- You’re overwriting the same array index every time you reset the timer
- You’re resetting the press counter before storing its value to the array
Step-by-Step Fix
Let’s walk through a corrected version of your logic, with clear explanations:
1. Clean Up Variables & Initialize Properly
First, rename variables for clarity (avoid ambiguous names like rate) and ensure your array is initialized once, not every timer reset:
public class PressRateTracker : MonoBehaviour { private float cycleTimer = 0f; public float cycleDuration = 1f; // How long each measurement cycle lasts private int currentCyclePresses = 0; // Counts presses in the active cycle private int[] cyclePressHistory = new int[2]; // Stores last two cycle counts private int activeHistoryIndex = 0; // Tracks which array slot to use next }
2. Correct the Cycle Reset Logic
The key fix is storing the current cycle’s press count before resetting the counter, and switching the array index after storage:
void Update() { // Run the cycle timer cycleTimer += Time.deltaTime; // Count key presses (example uses Space bar; adjust to your input) if (Input.GetKeyDown(KeyCode.Space)) { currentCyclePresses++; } // Trigger cycle reset when timer hits the limit if (cycleTimer >= cycleDuration) { // Store the current cycle's press count in the array cyclePressHistory[activeHistoryIndex] = currentCyclePresses; // Calculate rate once we have two cycles of data if (activeHistoryIndex == 1) { // Option 1: Current cycle's press rate (per second) float currentRate = currentCyclePresses / cycleDuration; Debug.Log($"Current Press Rate: {currentRate} presses/sec"); // Option 2: Rate change between the last two cycles float rateDifference = (cyclePressHistory[1] - cyclePressHistory[0]) / cycleDuration; Debug.Log($"Rate Change: {rateDifference} presses/sec"); } // Reset for the next cycle currentCyclePresses = 0; cycleTimer = 0f; // Switch to the next array index (cycles between 0 and 1) activeHistoryIndex = (activeHistoryIndex + 1) % 2; } }
Key Fixes Explained
- Per-cycle counting:
currentCyclePressesresets every cycle, so we’re storing the number of presses only for that cycle, not a cumulative total. - Proper storage timing: We save the press count to the array before resetting it, ensuring we capture the actual value from the cycle.
- Index cycling: Using
(activeHistoryIndex + 1) % 2ensures we alternate between the two array slots, so we never overwrite the previous cycle’s data immediately.
Additional Checks
- Make sure you’re not reinitializing the
cyclePressHistoryarray inside the reset logic (e.g.,rate_nums = new int[2];every time the timer resets) — this would wipe previous data and lead to duplicates. - Verify your input detection logic (e.g.,
Input.GetKeyDownworks as expected; it should only register one press per key press, not holding the key).
内容的提问来源于stack exchange,提问作者pyth12
相关产品推荐
相关产品推荐

