【问题标题】:Unity, why so many prefabs are getting generated?Unity,为什么会生成这么多预制件?
【发布时间】:2021-05-24 04:47:40
【问题描述】:

代码在这里:

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);
    }
}

我想在某个时间间隔后随机实例化预制件,但不知何故会生成大量预制件。我希望在时间间隔后在随机位置实例化一个预制件......有人请帮忙

【问题讨论】:

    标签: c# unity3d game-development


    【解决方案1】:

    每次调用 Update() 时,您都会重新调用 invokeRepeating。每次调用它都会添加另一个要重复的任务。

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

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

    【讨论】:

      【解决方案2】:

      您在 update() 中使用了 invokerepeating() 函数。这就是生成太多预制件的原因。从 update() 中删除 invokerepeating() 并在 start() 或 oneenable() 中尝试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-16
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 2014-10-19
        • 2021-11-03
        • 1970-01-01
        相关资源
        最近更新 更多