基础篇6 关于基类

jessy jessy #unity#unity引擎学习博客

关于基类的应用

关于基类的应用

相关文档:基类的使用 ,b站视频45

基类的创建

关于创建基础类的操作在rider中

在类的后面右键 - Refactor - Extract - Extract superclass(提取基类)

他的作用相当于把public(可以选择其他类型代码)的代码放到一起定义,然后让运行的代码显得没有这么累赘。

相当于创建了一个库,这个库相当于一个公共的库,里面都是共有的代码,就不需要每个文件打相同的代码,直接代上去就行

基类(Extract superclass)代码如下:

using System;
[Serializable]
public class Monster
{
public string Name; //名字
public int age;//年龄
public int hp;//血量
public string color;//颜色
public Monster(string name, int age, int hp, string color)
{
Name = name;
this.age = age;
this.hp = hp;
this.color = color;
}
public Monster()
{
}
}
  • 补充一点,在英文中,这个基类属于接口的意思(interface)

基类的使用

使用这个类我们直接在类名的右边加上去即可

代码如下:

using System;
using Unity.VisualScripting;
using UnityEngine;
[Serializable]
public class Dragon:Monster
{
//无参构造方法
public Dragon()
{
}
//全参构造函数
public Dragon(string name, int age, int hp, string color) : base(name, age, hp, color)
{
}
public void Rain()
{
Debug.Log($"一条名为{Name}{color}的龙正在云上翻滚倒腾,整个天空电闪雷鸣,大地仿佛被泼龙一盘大水。。");
}
}