试图统一调用方法。无法调用方法
Trying to invoke method in unity. Method cannot be called
void Update()
{
if (currentTarget != null)
{
this.Invoke("Shoot(currentTarget)", 0.3f);
}
}
void Shoot(Collider currentTarget)
{
.......
}
我希望快速调用 Shoot 方法。但我得到的只是
Trying to Invoke method: Tower.Shoot(currentTarget) couldn't be called.
可能是什么问题?
您不能使用参数调用调用。如果您从拍摄功能中删除参数,这应该有效。
Invoke("Shoot", 3f);
那么你的拍摄功能应该是这样的
void Shoot(){
}
而不是
void Shoot(string...parameter){
}
在您发表评论后,还有另一种方法可以做到这一点。这需要“Coroutine”。
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);
。
void Update()
{
if (currentTarget != null)
{
this.Invoke("Shoot(currentTarget)", 0.3f);
}
}
void Shoot(Collider currentTarget)
{
.......
}
我希望快速调用 Shoot 方法。但我得到的只是
Trying to Invoke method: Tower.Shoot(currentTarget) couldn't be called.
可能是什么问题?
您不能使用参数调用调用。如果您从拍摄功能中删除参数,这应该有效。
Invoke("Shoot", 3f);
那么你的拍摄功能应该是这样的
void Shoot(){
}
而不是
void Shoot(string...parameter){
}
在您发表评论后,还有另一种方法可以做到这一点。这需要“Coroutine”。
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);
。