如何在 Unity 中的特定时间段内生成预制件?

我正在尝试以棒球格式创建击球游戏。我创建了一个球作为预制件。我想在一定时间内把球推到主场景。


例如; 当第一个球在场景中时,第二个球会在 5-6 秒后生成,然后是第三个、第四个等等。我是 Unity 的初学者级别,我不擅长 C#。我不确定我是否使用了真正的函数,例如 Instantiate。这是我的脚本:


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class Ball : MonoBehaviour {

    public float RotateSpeed = 45; //The ball rotates around its own axis

    public float BallSpeed = 0.2f; 


    public GameObject[] prefab;


    public Rigidbody2D rb2D;


    void Start() {

        rb2D = GetComponent<Rigidbody2D>(); //Get component attached to gameobject

        Spawn ();

    }


    void FixedUpdate() {

        rb2D.MoveRotation(rb2D.rotation + RotateSpeed * Time.fixedDeltaTime); //The ball rotates around its own axis

        rb2D.AddForce(Vector2.left * BallSpeed);

        InvokeRepeating("Spawn", 2.0f, 2.0f);


    }


    public void Spawn () 

    {

        int prefab_num = Random.Range(0,3);

        Instantiate(prefab[prefab_num]);

    }


}

应用这个脚本后,结果不是我想要的。

http://img4.mukewang.com/60e902c500018c1710240580.jpg

慕码人8056858
浏览 295回答 3
3回答

月关宝盒

其他答案的替代方案:只需使用倒计时。这有时会给你更多的控制// Set your offset here (in seconds)float timeoutDuration = 2;float timeout = 2;void Update(){&nbsp; &nbsp; if(timeout > 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Reduces the timeout by the time passed since the last frame&nbsp; &nbsp; &nbsp; &nbsp; timeout -= Time.deltaTime;&nbsp; &nbsp; &nbsp; &nbsp; // return to not execute any code after that&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; // this is reached when timeout gets <= 0&nbsp; &nbsp; // Spawn object once&nbsp; &nbsp; Spawn();&nbsp; &nbsp; // Reset timer&nbsp; &nbsp; timeout = timeoutDuration;}
打开App,查看更多内容
随时随地看视频慕课网APP