当我们创建一个player时,设置了刚体,转向,检测地面等方法或属性;
而当我们创建其他角色或敌人时,也要用到这些东西。
为此,我们可以创建一个“模板”,方便之后引用这些方法或属性。
如:
public class entity : MonoBehaviour
public class Player : entity
entity类继承了MB类,而Player类继承了entity类
那么Player类就能以entity类为模板进行扩充
另外,在“模板”类中,所有的属性和方法前面都要以protected为前缀
如:
[SerializeField] protected float groundcheck;
protected Rigidbody2D rb;
protected bool isground;
protected virtual void Start()
{
rb = GetComponent<Rigidbody2D>();
a = GetComponentInChildren<Animator>();}
protected virtual void checkground()
{
isground = Physics2D.Raycast(gc.position, Vector2.down, groundcheck, whatisground);
}
当一个方法被标记为protected时,它可以在定义了该方法的类内部或者该类的子类中被访问。这意味着可以在继承了包含protected方法的类的子类中访问和重写这个方法。
同时,方法的前面要加上virtual,表示该方法可以在子类中被重写。
protected override void Start()
{
base.Start();
}
在子类中,通过override对父类进行重写,注意要保留父类的名称和修饰符。