为什么我的障碍物生成不遵循相同的生成模式?

Why does my obstacle spawn not follow the same spawning pattern?

我正在制作一个游戏,您可以在其中移动 3 个方块,其中两个方块中有障碍物,这是一张图片 picture of game。我遇到的问题是,障碍物有时会休息 3 秒,然后再次生成,然后等待一段时间并再次开始生成。图案不连续。我希望它们总是在中间产生一秒钟。

  using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

public class merHinder : MonoBehaviour
{
    public Rigidbody2D orginal;
    private Vector3[] spawnPos = new Vector3[3];


    // Start is called before the first frame update
    void Start()
    {
        //InvokeRepeating("timer", 0f, 1f);
        StartCoroutine(SpawnAtIntervals(1f));
    }

    // Update is called once per frame
    void Update()
    {


        spawnPos[0] = new Vector3(3, 3.86f, -5);
        spawnPos[1] = new Vector3(-3, 3.86f, -5);
        spawnPos[2] = new Vector3(0, 3.86f, -5);




    }
    private void FixedUpdate()
    {

    }
    void Spawn()
    {
        int randomNumber = Random.Range(0, spawnPos.Length);
        int randomNumber1 = Random.Range(0, spawnPos.Length);
        if (randomNumber != randomNumber1)
        {
            Rigidbody2D clone1 = Instantiate(orginal, spawnPos[randomNumber], Quaternion.identity);
            Rigidbody2D clone2 = Instantiate(orginal, spawnPos[randomNumber1], Quaternion.identity);
        }
        //Destroy(orginal);



    }
    bool keepSpawning = true;

    IEnumerator SpawnAtIntervals(float secondsBetweenSpawns)
    {
        // Repeat until keepSpawning == false or this GameObject is disabled/destroyed.
        while (keepSpawning)
        {
            // Put this coroutine to sleep until the next spawn time.
            yield return new WaitForSeconds(secondsBetweenSpawns);

            // Now it's time to spawn again.
            Spawn();
        }
    }
}

它们只会在随机数不同时生成。但有时随机结果相同。

    int randomNumber = Random.Range(0, spawnPos.Length);
    int randomNumber1 = Random.Range(0, spawnPos.Length);
    if (randomNumber != randomNumber1) // <- No spawn if both random numbers are the same
    {
        Rigidbody2D clone1 = Instantiate(orginal, spawnPos[randomNumber], Quaternion.identity);
        Rigidbody2D clone2 = Instantiate(orginal, spawnPos[randomNumber1], Quaternion.identity);
    }

可能的解决方案(有点老套,但没有堆分配):

    void Spawn()
        {
            int randomNumber = Random.Range(0, spawnPos.Length);
            int randomNumber1 = Random.Range(0, spawnPos.Length);
            while (randomNumber == randomNumber1)
            {
                // try again until numbers are different
                randomNumber1 = Random.Range(0, spawnPos.Length);
            }
            Rigidbody2D clone1 = Instantiate(orginal, spawnPos[randomNumber], Quaternion.identity);
            Rigidbody2D clone2 = Instantiate(orginal, spawnPos[randomNumber1], Quaternion.identity);
        }