为鱼挂上属性脚本,并且将鱼死亡动画创作预制件,赋值
当然还需要给鱼初始化生命值
FishAttribute.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishAttribute : MonoBehaviour
{
// 一波鱼生成的最大数量
public int maxNum;
// 最大速度
public int maxSpeed;
// 鱼的生命值
public int hp;
// 鱼的死亡动画
public GameObject diePrefab;
// 判定鱼出界然后销毁
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Border")
{
Destroy(gameObject);
}
}
void ReceiveDamage(int damage)
{
hp -= damage;
if (hp <= 0)
{
// 死亡动画初始化
GameObject die = Instantiate(diePrefab);
die.transform.SetParent(gameObject.transform.parent, false);
// 位置
die.transform.position = transform.position;
die.transform.rotation = transform.rotation;
Destroy(gameObject);
}
}
}
鱼死亡的原因是生命值降到0,计算该生命值得时候在网属性里面调用ReceiveDamage方法
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Fish")
{
// 给鱼发消息让鱼受伤,传入伤害值
collision.SendMessage("ReceiveDamage", dama
ge);
}
}
网友评论