unity中继承的学习记得断点后运行理解下哈

本文探讨了Unity游戏开发中C#语言的继承概念。通过设置断点并实际运行代码,作者详细解释了如何在Unity环境中应用继承,以实现代码复用和类之间的关系。通过对基类和派生类的操作,读者可以更深入地理解继承在实际项目中的工作原理。
摘要由CSDN通过智能技术生成
using UnityEngine;

public class Inheritance : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Creating the fruit");
        Fruit myFruit = new Fruit();
        Debug.Log("Creating the apple");
        Apple myApple = new Apple();

        //调用 Fruit 类的方法。
        myFruit.SayHello();
        myFruit.Chop();

        //调用 Apple 类的方法。
        //注意 Apple 类如何访问
        //Fruit 类的所有公共方法。
        myApple.SayHello();
        myApple.Chop();

        //现在,让我们用读取字符串的
        //构造函数来说明继承。
        Debug.Log("Creating the yellow fruit");
        myFruit = new Fruit("yellow");
        Debug.Log("Creating the  green apple");
        myApple = new Apple("green");

        //调用 Fruit 类的方法。
        myFruit.SayHello();
        myFruit.Chop();

        //调用 Apple 类的方法。
        //注意 Apple 类如何访问
        //Fruit 类的所有公共方法。
        myApple.SayHello();
        myApple.Chop();
    }

  
}

public class Fruit
{
    public string color;
    public Fruit()
    {
        color = "orange";
        Debug.Log("1st Fruit Constructor Called");
    }

    public Fruit(string newColor)
    {
        this.color = newColor;
        Debug.Log("2nd Fruit Constructor Called");
    }

    public void Chop()
    {
        Debug.Log("The " + color + " fruit has been chopped.");
    }
    public void SayHello()
    {
        Debug.Log("Hello, I am a fruit.");
    }
}

public class Apple : Fruit
{
    public Apple()
    {
        color = "red";
        Debug.Log("1st Apple Constructor Called");
    }

    public Apple(string newColor):base(newColor)
    {
        Debug.Log("2nd Apple Constructor Called");
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值