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

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: currentCyclePresses resets 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) % 2 ensures 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 cyclePressHistory array 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.GetKeyDown works as expected; it should only register one press per key press, not holding the key).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:20:03