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

如何实现1-10范围内不重复随机数生成?附Unity代码优化需求

Solution for Generating Unique Random Numbers (1-10) in Unity

Let's tweak your code to generate non-repeating random numbers between 1 and 10, with automatic retries when duplicates are found, and a clear message when all numbers are used up. Here's a complete, tested implementation:

using UnityEngine;
using System.Collections.Generic;

public class UniqueNumberGenerator : MonoBehaviour
{
    public int number;
    // Track used numbers for fast duplicate checks
    private HashSet<int> usedNumbers = new HashSet<int>();
    // Total unique values we need to cover (1 through 10)
    private const int totalUniqueNumbers = 10;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            // First check if all numbers are already used
            if (usedNumbers.Count >= totalUniqueNumbers)
            {
                Debug.Log("All numbers from 1 to 10 have been used! No more unique values available.");
                return;
            }

            int newNumber;
            // Keep generating numbers until we find one that hasn't been used yet
            do
            {
                // Note: Unity's int Random.Range is left-inclusive, right-exclusive
                // So 1,11 gives us values from 1 to 10 (your original code only went up to 9!)
                newNumber = Random.Range(1, 11);
            } while (usedNumbers.Contains(newNumber));

            // Save the unique number and assign it to your public variable
            usedNumbers.Add(newNumber);
            number = newNumber;
            Debug.Log($"Generated unique number: {number}");
        }
    }
}

Key Details to Note:

  • HashSet usedNumbers: This collection makes checking for duplicates super fast (way more efficient than a List for lookups, though either works for a small set like 10 numbers).
  • Random.Range(1, 11): Critical fix! Your original code used Random.Range(1,10), which only generates numbers from 1 to 9 (since Unity excludes the upper bound for integer ranges). Using 11 as the upper limit gets us the full 1-10 range.
  • Do-While Loop: Automatically retries generating numbers until it finds one that's not already in our used set—exactly what you asked for.
  • Full Set Check: Prevents infinite looping by checking if we've exhausted all unique values before trying to generate a new one.

Alternative with List (If You Prefer):

If you'd rather use a List<int> instead of a HashSet, the logic is nearly identical—just swap out the collection type. It works just fine for small datasets like this:

private List<int> usedNumbers = new List<int>();
// ... inside the input check:
do
{
    newNumber = Random.Range(1, 11);
} while (usedNumbers.Contains(newNumber));
usedNumbers.Add(newNumber);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:11:13