我复制了游戏的第1级。我想让它的工作方式与第1级相同,只需添加前一个。脚本和对撞机附加到预制件,其中对撞机功能用于同一脚本的两个类中。我在脚本中使用两个类。在我的游戏的第2级,我想调用第二个类,并希望脚本执行第二类的碰撞器功能。我怎样才能在二级打电话给二等?请帮我。谢谢。
public class class1: Monobehaviour {
//public variables declaration
void OnTriggerEnter2d(){}
}
public class class2: Monobehaviour {
//public variables declaration
void OnTriggerEnter2d(){}
}
答案 0 :(得分:0)
您可以创建一个接口,让两个类实现相同的接口。
public interface ITriggerBehaviour
{
void OnTriggerEnter2d();
}
public class class1: Monobehaviour, ITriggerBehaviour
{
//public variables declaration
void OnTriggerEnter2d(){}
}
public class class2: Monobehaviour, ITriggerBehaviour
{
//public variables declaration
void OnTriggerEnter2d(){}
}
然后,在不知道哪个类实现该方法的情况下,您可以使用相同的名称来调用它。
public void SomeOtherFunction()
{
// In your code, the object will be provided elsewhere, in which case
// you may want to use the 'as' operator to convert the object
// reference to the interface and test for 'null' before using it.
// This example shows that an interface can be used to hold a reference
// to different types of object, providing they both implement the
// same interface.
ITriggerBehaviour someObject;
if(currentLevel == 1)
someObject = new class1();
else
someObject = new class2();
// Call the method via the interface
someObject.OnTriggerEnter2d();
}