只有在特定攻击动画完成后才实例化对象的查询

3

当我点击攻击按钮时,我的玩家Robot会进行攻击。 我正在使用coroutine等待一段时间,然后从firepos位置实例化激光。

请看下面的gif以便更好的理解:

error in shoot time

现在,如果您看上面的gif,您会发现,如果我按住攻击按钮,玩家会进行动画,并根据waitForSecondscoroutine在一秒钟后射出激光。这很好!

但是,当我在短时间内多次突然点击按钮时,动画不播放(我可以理解...这是显而易见的!),但是类似于上述情况,由于waitforseconds和由于我点击了几次,同样数量的激光射出,这是我不想要的!

我想要的是:当我单击并按住攻击按钮时,动画应该完成,然后才能射出激光。

并且

如果我在短时间内多次点击该按钮,则不应射出激光(它是一个预制件被实例化)。

只有当动画完成后,激光才会射出。

现在我无法解决这个问题! 有人能帮忙吗?

在检查器中对攻击按钮进行设置:

laser button

我在OnpointerDownup中调用两个函数

函数代码:

public void LaserAttack(){
        isAttacking = true;
        StartCoroutine (AttackStillCoroutine ());

        if (robotLeft == true&&isLaserLeft==false) {

            //Debug.Log (firep.position.x);

            //Instantiate (leftLaser, firep.position*1.29f, Quaternion.identity);

            StartCoroutine( DelayMethodLeftInstantiate());

        } 

        if (robotRight == true&&isLaserLeft==false) {

            StartCoroutine(  DelayMethodRightInstantiate());

            //Instantiate (RightLaser, firep.position, Quaternion.identity);
        }
        anim.SetBool ("isAttack", isAttacking);
        isLaserLeft = true;

    }

    public void LaserAttackEnd(){
        isAttacking = false;
        attackStill = false;
        anim.SetBool ("isAttackStill",attackStill);
        anim.SetBool ("isAttack", isAttacking);
        isLaserLeft = false;

    }

协程代码(左右两个)如下:

IEnumerator DelayMethodLeftInstantiate(){

        yield return new WaitForSeconds(1);
        Instantiate (leftLaser, firep.position, Quaternion.identity);
    }

    IEnumerator DelayMethodRightInstantiate(){

        yield return new WaitForSeconds(1);
        Instantiate (RightLaser, firep.position, Quaternion.identity);
    }

请帮忙,对不起我对这方面的知识很少...大家好,我是新手!


这里有一个答案,我猜在这种情况下谷歌是最好的答案:答案 - Shakra
1个回答

1

有两种方法可以解决您的问题。

首先,如果按钮被释放,您可以停止协程。

您可以使用IPointerUpHandler(我假设您从UI按钮调用该方法)

public class InputHandler, MonoBehaviour, IPointerUpHandler
{
    IEnumerator coroutine = null;
    public void LaserAttack(){
        isAttacking = true;
        this.coroutine = AttackStillCoroutine ()
        StartCoroutine (this.coroutine);
       // More code
    }
    public void OnPointerUp(PointerEventData eventData)
    {
         if(this.isAttacking == true && this.coroutine != null ){
             StopCoroutine(this.coroutine);
             this.coroutine = null;
         }
    }
}

另一种我推荐的方法是使用AnimationEvent。您可以将一个方法委托放置到您的动画中,以便在达到该点时调用该方法。
我会粘贴一个链接,因为它比代码更加直观:

https://docs.unity3d.com/Manual/animeditor-AnimationEvents.html


我已经在使用IpointerUpHandlerDownHandler来实现UI事件触发器PointerDown的连续移动(左右)。我不想添加更多代码使其变得更加复杂。但是你提出的第二种AnimationEvent方法是最好的,太棒了! - utkdub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接