尝试在统一中调用方法.无法调用方法

本文关键字:调用 方法 | 更新日期: 2023-09-27 18:37:23

void Update()
{
    if (currentTarget != null)
    {
        this.Invoke("Shoot(currentTarget)", 0.3f);
    }
}
void Shoot(Collider currentTarget)
{
    .......
}

我希望快速调用 Shot 方法。但我得到的只是

Trying to Invoke method: Tower.Shoot(currentTarget) couldn't be called.

可能有什么问题?

尝试在统一中调用方法.无法调用方法

不能 使用 参数调用 Invoke。如果您从 Shot 函数中删除参数,这应该有效。

Invoke("Shoot", 3f);

那么你的拍摄功能应该看起来像这样

void Shoot(){
}

而不是

void Shoot(string...parameter){
}

在您发表评论后,还有另一种方法可以做到这一点。这需要"协程"。

 IEnumerator Shoot(Collider currentTarget, float delayTime)
     {
         yield return new WaitForSeconds(delayTime);
         //You can then put your code below
       //......your code
     }

您不能直接调用它。例如,您不能这样做: Shoot(currentTarget, 1f) ;

您必须使用**StartCoroutine**(Shoot(currentTarget, 1f));

 void Start()
 {
    //Call your function
     StartCoroutine(Shoot(currentTarget, 1f));
 }

此外,如果您不喜欢使用 StartCoroutine,则可以在另一个普通函数中调用协程函数。我想你可能喜欢这个方法,所以整个代码应该看起来像下面:

 //Changed the name to **ShootIEnum**
 IEnumerator ShootIEnum(Collider currentTarget, float delayTime=0f)
     {
         yield return new WaitForSeconds(delayTime);
         //You can then put your code below
       //......your code
     }
//You call this function 
void Shoot(Collider currentTarget, float delayTime=0f)
{
 StartCoroutine(ShootIEnum(currentTarget, 1f));
}
void Update()
    {
        if (currentTarget != null)
        {
           Shoot(currentTarget,  0.3f);
        }
    }

现在,只要您想打电话给Shoot,您现在就可以毫无问题地拨打Shoot(currentTarget, 1f);