C# Unity,为什么会生成这么多预制件?

C# Unity,为什么会生成这么多预制件?,c#,unity3d,game-development,C#,Unity3d,Game Development,代码如下: using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnManager : MonoBehaviour { public GameObject[] animalprefabs; public float spawninterval = 2.5f; public float spawnDelay = 2.0f; //

代码如下:

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

public class SpawnManager : MonoBehaviour
{
    public GameObject[] animalprefabs;
    public float spawninterval = 2.5f;
    public float spawnDelay = 2.0f;
    // Start is called before the first frame update
    void Start()
    {
        
    }

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

         InvokeRepeating("spawnRandomAnimal",spawnDelay, spawninterval);
        
    }

    void spawnRandomAnimal()
    {
        int animalIndex = Random.Range(0, animalprefabs.Length);
        int SpawnIndex = 20;
        Vector3 spawnPosition = new Vector3(Random.Range(-SpawnIndex, SpawnIndex), 0, 25);
        Instantiate(animalprefabs[animalIndex], spawnPosition ,animalprefabs[animalIndex].transform.rotation);
    }
}

我想在某个时间间隔后随机实例化一个预制件,但不知怎么的,大量的预制件正在生成。我想在时间间隔后的一个随机位置实例化一个预制件。。。每次调用
Update()
时,都有人向您正在调用的
invokererepeating
提供帮助。每次调用它时,都会添加另一个要重复的任务

移动它以开始解决您的问题

void Start()
{
    InvokeRepeating("spawnRandomAnimal",spawnDelay, spawninterval);
}

您正在update()中使用invokerepeating()函数。这就是为什么会生成太多的预制件。从update()中删除invokerepeating(),然后在start()或onenable()中尝试