unity->C#简单的继承

本文介绍了如何在Unity中使用C#进行简单的继承操作。通过创建一个Vehicle基类,包含Run、Stop方法以及Speed、MaxSpeed、Weight属性,然后分别派生出car和bicycle类。在派生类中重写Run和Stop方法,并在实例化后调用这些方法,验证了继承功能的正确性。

简单的继承

定义一个车辆(Vehicle)基类,具有Run、Stop等方法,具有Speed(速度)、MaxSpeed(最大速度)、Weight(重量)等域。然后以该类为基类,派生出bicycle、car等类。并编程对该派生类的功能进行验证。

父类

using UnityEngine;

using System.Collections;

public class Vehicle {
    public float Speed;
    public float MaxSpeed;
    public float Weight;
    public void Run()
    {
        Debug.Log("Vehicle-Run");
    }
    public void Stop()
    {
        Debug.Log("Vehicle-Stop");
    }

}

--------------------------

子类

using UnityEngine;
using System.Collections;

public class car :Vehicle {
    public void Run()
    {
        
        Debug.Log("car-Run"+"speed->"+Speed+"\t"+"Weight->"+Weight+"\t"+"MaxSpeed"+MaxSpeed);
    }
    public void Stop()
    {
        Debug.Log("car-Stop"+"speed->"+Speed+"\t"+"Weight->"+Weight+"\t"+"MaxSpeed"+MaxSpeed);
    }
}



using UnityEngine;
using System.Collections;

public class bicycle : Vehicle {
    public void Run()
    {        
        Debug.Log("bicycle-Run"+"speed->"+Speed+"\t"+"Weight->"+Weight+"\t"+"MaxSpeed"+MaxSpeed);
    }
    public void Stop()
    {
        Debug.Log("bicycle-Stop"+"speed->"+Speed+"\t"+"Weight->"+Weight+"\t"+"MaxSpeed"+MaxSpeed);
    }
}

-----------------------

引用

using UnityEngine;
using System.Collections;

public class chen : MonoBehaviour {

    public bicycle s1=new bicycle();
    public car s2=new car();
    void Start () {
        s1.Speed = 30;
        s1.MaxSpeed = 90;
        s1.Weight = 1000;
        s2.Speed = 50;
        s2.MaxSpeed = 120;
        s2.Weight = 1500;
        s1.Run ();
        s1.Stop ();
        s2.Run ();
        s2.Stop ();
    }
    void Update () {
    
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值