如何在等待10秒后重置球
本文关键字:10秒 在等待 | 更新日期: 2023-09-27 18:20:25
我正试图在投球后延迟10秒重置球球停得很好。但是如何延迟球复位请帮我。球复位太快。我也用过这个功能,但它不能正常工作,请帮帮我我在比赛的最后阶段。
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public Vector3 launchVeclocity;
//private const float RESET_TIME = 5.0f; // time to be taken for reset
public bool inPlay = false;
private Vector3 ballStartPos;
private Rigidbody rigidBody;
private AudioSource audioSource;
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody>();
//rigidBody.useGravity = false;
ballStartPos = transform.position;
}
public void Launch (Vector3 velocity)
{
inPlay = true;
rigidBody.useGravity = true;
rigidBody.velocity = velocity;
audioSource = GetComponent<AudioSource> ();
audioSource.Play ();
}
void Update() {
Waiting ();
}
public void Reset() {
inPlay = false;
//yield return new WaitForSeconds (5);
transform.position = ballStartPos;
transform.rotation = Quaternion.identity;
rigidBody.velocity = Vector3.zero;
rigidBody.angularVelocity = Vector3.zero;
rigidBody.useGravity = false;
}
IEnumerator Waiting ()
{
Reset ();
yield return new WaitForSeconds (10);
}
}
您不应该像当前那样在Update()中调用协程来在每一帧上启动该协程(但这不是您问的问题)。但它实际上没有等待的原因是,您直接调用waiting(),而不是使用StartCoroutine(Waitin())。
我假设Launch
是投球的方法。
首先,从Update
方法中删除对Waiting()
的调用,您不希望像那样直接调用Waiting()
方法。您需要在Launch方法中启动一个Coroutine:
public void Launch (Vector3 velocity)
{
inPlay = true;
rigidBody.useGravity = true;
rigidBody.velocity = velocity;
audioSource = GetComponent<AudioSource> ();
audioSource.Play ();
// start the Coroutine to introduce the reset delay
StartCoroutine(Waiting());
}
IEnumerator Waiting ()
{
// suspect executing in this routine for 10 seconds
yield return new WaitForSeconds (10);
// now call reset
Reset();
}
使用Invoke()会更容易。你已经有了这个方法,所以它只需要这个作为你的Launch()方法:
public void Launch (Vector3 velocity)
{
inPlay = true;
rigidBody.useGravity = true;
rigidBody.velocity = velocity;
audioSource = GetComponent<AudioSource> ();
audioSource.Play ();
Invoke("Reset", 10);
}
你可以去掉整个Waiting()
方法
Systeam.Threading.Thread.Sleep
IEnumerator Waiting ()
{
Reset ();
yield return Thread.Sleep(10000); // In miliseconds.
}