unity3d 移动之间的时间减少为单位WaitForSeconds

vc9ivgsu  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(185)

我试图在x轴上移动块,移动之间有延迟

public class setmove : MonoBehaviour
{
 Transform trans
 private void Start()
{
 trans = GetComponet<Transform>();
}
private void Update()
{
 if(trans.position.x != -15 { StartCoroutine(wait(20)); }
//this is here to make new block and destroy old one
 if(trans.position.x <= -15 { GameObject .find("controller").GetComponet<set_make>().Start(); Destroy(this); }
private IEnumerator wait(int delay)
{
 yield return new WaitForSecondsRealTime(delay);
 trans.position = new vector3(trans.position.x-1, trans.position.y);
}
}

但没有延迟
我希望它等待,但间隔时间会缩短

5us2dqdw

5us2dqdw1#

1.一个float几乎永远不会恰好是一个值(floating point inaccuracies

  1. Update每帧运行一次=〉只要满足条件,您将在每帧启动数百个并发协程。
    你可能应该只有一个单一的例行程序和
// yes, start can be a Coroutine itself
// Unity will automatically run it as Coroutine if it returns IEnumerator
private IEnumerator Start() 
{
    while(transform.position.x > -15) 
    {
        yield return new WaitForSecondsRealtime(20);

        transform.position += Vector3.left;
    }

    // "Find" is capital "F"! C# is case sensitive
    // could probably also use `FindObjectOfType<set_make>
    // you should avoid calling `Start` from the outside
    // It is a " magic" message and will anyway be called by the engine automatically
    // so it is at best confusing to call it from anyway else again
    GameObject.Find("controller").GetComponet<set_make>().Start();
    // note that if using "this" You only destroy the component, not the obbect
    Destroy (this.gameObject) ;
}

相关问题