0

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

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

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

}

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

在此处输入图像描述

4

4 回答 4

3

添加InvokeRepeating("Spawn", 2.0f, 2.0f);StartFixedUpdate. InvokeRepeating在 time 秒内调用该方法methodName,然后每秒重复一次repeatRate您可以在此处查看文档。

于 2018-05-28T20:56:06.217 回答
2

使用协程

private IEnumerator SpawnBall() {
    while(true) {
        Instantiate(baseball);
        yield return new WaitForSeconds(5);
    }
}

然后可以通过StartCoroutine()以下三种方式之一启动和终止:

  • 通过在内部中断while循环break(该函数将没有更多行来执行和退出)
  • 内部由yield break
  • StopCoroutine()通过调用对协程的引用从外部调用
于 2018-05-29T01:20:17.023 回答
2

其他答案的替代方案:只需使用倒计时。这有时会给你更多的控制权

// Set your offset here (in seconds)
float timeoutDuration = 2;

float timeout = 2;

void Update()
{
    if(timeout > 0)
    {
        // Reduces the timeout by the time passed since the last frame
        timeout -= Time.deltaTime;

        // return to not execute any code after that
        return;
    }

    // this is reached when timeout gets <= 0

    // Spawn object once
    Spawn();

    // Reset timer
    timeout = timeoutDuration;
}
于 2018-05-29T16:38:35.840 回答
0

我通过考虑您的反馈更新了我的脚本,它就像一个魅力。谢谢大家!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Threading;

public class Ball : MonoBehaviour {
    public float RotateSpeed = 45; //The ball rotates around its own axis
    public float BallSpeed = 0.2f; 

    public GameObject BaseBall;
    public Transform BallLocation;

    public Rigidbody2D Ball2D;

    void Start() {
        Ball2D = GetComponent<Rigidbody2D>(); //Get component attached to gameobject
        InvokeRepeating("Spawn", 5.0f, 150f);
    }       

    void FixedUpdate() {
        Ball2D.MoveRotation(Ball2D.rotation + RotateSpeed * Time.fixedDeltaTime); //The ball rotates around its own axis
        Ball2D.AddForce(Vector2.left * BallSpeed);
    }

    public void Spawn () 
    {
        Instantiate (BaseBall, BallLocation.position, BallLocation.rotation);
    }
}
于 2018-06-05T17:27:20.590 回答