当其他协程已经在运行时,如何让协程启动并继续工作?

该脚本附着在 3 个立方体上。每个立方体都有另一个标签。


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class raytest : MonoBehaviour

{

    public float duration;

    public string tag;


    private Vector3 originalpos;


    private void Start()

    {

        originalpos = transform.position;

    }


    private void Update()

    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit hit;


        if (Physics.Raycast(ray, out hit, 100))

        {

            if (hit.transform.tag == tag)

            {

                 if (transform.position.z != originalpos.z - 1)

                   StartCoroutine(moveToX(transform, new Vector3(transform.position.x, transform.position.y, transform.position.z - 1), duration));

            }

            else

            {

                 StartCoroutine(moveToX(transform, originalpos, duration));

            }

        }

        else

        {

             //reset

             StartCoroutine(moveToX(transform, originalpos, duration));

        }

    }


    bool isMoving = false;

    IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)

    {

        //Make sure there is only one instance of this function running

        if (isMoving)

        {

            yield break; ///exit if this is still running

        }

        isMoving = true;


        float counter = 0;


        //Get the current position of the object to be moved

        Vector3 startPos = fromPosition.position;


        while (counter < duration)

        {

            counter += Time.deltaTime;

            fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);

            yield return null;

        }


        isMoving = false;

    }

}

当鼠标悬停在游戏对象上并发射光线时,该对象开始移动。当光线没有击中物体时,物体就会移回到原来的位置。


但有时,当我将鼠标快速移动到两个甚至三个对象上时,下一个对象不会移动,直到第一个对象完成移动。有时,物体同时移动,第一个物体向前移动,而其余物体仍移回原始位置。


我不知道为什么有时当击中另一个物体时,它首先等待另一个物体回到原来的位置,然后才开始移动击中的物体?并且不要同时将它们一前一后移动。


这个想法是,如果我击中一个物体并开始向前移动,一旦我击中另一个物体,第一个物体应该开始向后移动,而击中的物体应该开始平行地向前移动。


隔江千里
浏览 54回答 2
2回答

牛魔王的故事

抱歉,如果我没有正确理解这个问题,但这就是我收集到的:如果光线投射击中物体,则其向单向移动,如果光线投射未击中物体,则其移回其原始位置。如果这就是您所需要的——协程不是让问题变得过于复杂了吗?例如,您可以将CheckIfRaycast.cs脚本附加到每个盒子上。在该脚本Update()方法中,您可以检查它是否被光线投射击中,然后进行所需的移动。多个协程可能会导致一些奇怪的行为,因此请确保使用StopCoroutine(coroutine name);或停止它们StopAllCoroutines();。

慕盖茨4494581

你应该这样识别你的协程:你必须在不同的对象上使用不同的协程Coroutine c1;Coroutine c2;void runCourotines(){&nbsp; &nbsp; c1 = StartCoroutine(MoveToX());&nbsp; &nbsp; c2 = StartCoroutine(MoveToX());}void StopCoroutines(){&nbsp; &nbsp; StopCoroutine(c1);}
打开App,查看更多内容
随时随地看视频慕课网APP