我正在尝试用棒球格式创建一个击球游戏。我创造了一个球作为预制件。我想在一段时间内把球推到主场面。
例如;当第一个球在场景中时,第二个球将在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]);
}
}
应用此脚本后,结果不是我想要的。
答案 0 :(得分:3)
将InvokeRepeating("Spawn", 2.0f, 2.0f);
添加到Start
而不是FixedUpdate
。
InvokeRepeating
在时间秒内调用方法methodName
,然后每隔repeatRate
秒重复一次。
您可以查看文档here。
答案 1 :(得分:1)
private IEnumerator SpawnBall() {
while(true) {
Instantiate(baseball);
yield return new WaitForSeconds(5);
}
}
然后可以使用StartCoroutine()
开始,然后以三种方式之一终止:
break
的while循环(该函数将不再有行执行和退出)yield break
StopCoroutine()
答案 2 :(得分:0)
替代其他答案:只需使用倒计时。这有时会给你更多的控制权
// 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;
}
答案 3 :(得分: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);
}
}