目录
一、创建基类
在unity中创建一个基类代码Item,此脚本不需要挂载在任何物体上,基类代码中所有的方法都会被派生类继承。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : MonoBehaviour
{
public float rotateSpeed = 180.0f;//旋转的速度
public GameObject hitEffect;//碰撞效果
void Update()
{
transform.Rotate(0, rotateSpeed * Time.deltaTime, 0);//物体旋转
}
public virtual void HitItem()
{
GameObject effect = Instantiate(hitEffect);//初始化粒子对象
effect.transform.parent = PlayerControl.instance.gameObject.transform;
effect.transform.localPosition = new Vector3(0, 0.5f, 0);
Destroy(gameObject);//当前物体消失
}
//触发器,other是碰撞到物体的主角
public virtual void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
HitItem();
//Destroy(gameObject);//当前物体消失
}
}
}
在此跑酷游戏demo中创建是金币、跑鞋等物品的基类。这些物品在运行中会自动旋转、主角碰到会消失且触发不同的功能,这些方法都是相同的,为了避免每一个物品代码都写一遍就创建一个包含这些方法的基类。但由于每个物品中使用功能不相同,因此在基类中使用虚方法,便于在各派生类中重写
二、创建派生类
创建派生类脚本,并将其挂载在对应的物体上,如金币和跑鞋
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : Item
{
public override void OnTriggerEnter(Collider other)
{
base.OnTriggerEnter(other);
if (other.tag == "Player")
{
AudioManager.instance.PlayCoinAudio();
GameAttribute.instance.addcoin();//金币数递加
}
}
}
继承了基类中的方法功能,如金币旋转、金币碰到主角就会消失。也有自己单独拥有的功能,以上代码重写了OnTriggerEnter(Collider other)方法的内容,在继承基类的基础上增加了一个if语句,如果金币碰到主角主角得到的金币数回增加,也播放主角吃到金币的音效,这两个功能的实现是金币与其它物品的不同之处。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shoe : Item
{
public override void OnTriggerEnter(Collider other)
{
base.OnTriggerEnter(other);
if(other.tag=="Player")
{
AudioManager.instance.PlaygetitemAudio();
PlayerControl.instance.UseShoe();
}
}
}
与金币一样继承了基类的方法和功能实现,不同的是重写虚方法中增加的功能是得到跑鞋后可以双连跳,播放音效。
跑鞋的双连跳和主角金币数的增加是在其它代码中写,以上两个派生类代码中只是调用它们的方法。
三、什么时候使用继承
如果一个几个物体都使用相同的方法,如多种敌人、物品等这种具有相同性的功能方法可以写在基类中
目录
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
public static PlayerControl instance;//单例
private void Awake()
{
Instance = this;//初始化
}
}
PlayerControl.instance.UseShoe();//调用基类方法