Unity3d 执行来自多个脚本的回调
Unity3d perform a callback from multiple scripts
我在 Unity 的 C# 脚本中遇到回调函数问题。
在Corona SDK中,如果你想执行回调,你只需要将它作为参数传递,然后在适当的地方调用它。
local function boom()
print("booom!!!")
end
local function bang()
print("baaaang!!!")
end
local function selector(var, func1, func2)
if var > 0 then
func1()
else
func2()
end
end
selector(5, boom, bang)
selector(-12, boom, bang)
我得到:
booom!!!
baaaang!!!
哪个是正确的。
但是当我尝试在 Unity 的 C# 脚本中实现它时,我遇到了很多问题。首先,仅仅传递一个参数是不够的。您需要在 selector()
函数中指定变量类型。所以我必须为 func1
和 func2
指定 class 名称。但是如果我希望能够从多个脚本中调用它并传递不同的回调函数呢?然后我无法将 class 指定为类型。
我找到的教程很少,但是 none 解决了我的问题。他们都描述了如何在 class 内或仅从预定义的 class
实际上它在 C# 中的工作方式非常相似,除了您必须明确类型之外:
void boom()
{
Debug.Log("booom");
}
void bang()
{
Debug.Log("baaaang");
}
void selector(int v, Action func1, Action func2)
{
if (v > 0)
func1();
else
func2();
}
...
selector(5, boom, bang);
selector(-12, boom, bang);
我在 Unity 的 C# 脚本中遇到回调函数问题。
在Corona SDK中,如果你想执行回调,你只需要将它作为参数传递,然后在适当的地方调用它。
local function boom()
print("booom!!!")
end
local function bang()
print("baaaang!!!")
end
local function selector(var, func1, func2)
if var > 0 then
func1()
else
func2()
end
end
selector(5, boom, bang)
selector(-12, boom, bang)
我得到:
booom!!!
baaaang!!!
哪个是正确的。
但是当我尝试在 Unity 的 C# 脚本中实现它时,我遇到了很多问题。首先,仅仅传递一个参数是不够的。您需要在 selector()
函数中指定变量类型。所以我必须为 func1
和 func2
指定 class 名称。但是如果我希望能够从多个脚本中调用它并传递不同的回调函数呢?然后我无法将 class 指定为类型。
我找到的教程很少,但是 none 解决了我的问题。他们都描述了如何在 class 内或仅从预定义的 class
实际上它在 C# 中的工作方式非常相似,除了您必须明确类型之外:
void boom()
{
Debug.Log("booom");
}
void bang()
{
Debug.Log("baaaang");
}
void selector(int v, Action func1, Action func2)
{
if (v > 0)
func1();
else
func2();
}
...
selector(5, boom, bang);
selector(-12, boom, bang);