1. 程式人生 > 其它 >Unity學習之重置內建運算子

Unity學習之重置內建運算子

技術標籤:筆記unity

直接上程式碼:

using UnityEngine;


/// <summary>
/// 
/// * Writer:June
/// 
/// * Date: 2021.1.30
/// 
/// * Function:過載內建運算子
/// 
/// * Remarks:可以過載除賦值號以外的符號運算
/// 
/// </summary>


public class OperatorTest : MonoBehaviour
{
    private void Start()
    {
        Hero hero1 = new Hero()
        {
            HP = 100,
            Attack = 200
        };
        Hero hero2 = new Hero()
        {
            HP = 500,
            Attack = 20
        };
        Debug.LogFormat("兩個不同例項做加法:\n 血量:{0} , 攻擊力:{1}", (hero1 + hero2).HP, (hero1 + hero2).Attack);
    }
}



class Hero
{
    public int HP { get; set; }
    public int Attack { get; set; }
    public static Hero operator -(Hero _hero1, Hero _hero2)
    {
        return new Hero
        {
            HP = _hero1.HP - _hero2.HP,
            Attack = _hero1.Attack - _hero2.Attack
        };
    }
    public static Hero operator +(Hero _hero1, Hero _hero2)
    {
        return new Hero
        {
            HP = _hero1.HP + _hero2.HP,
            Attack = _hero1.Attack + _hero2.Attack
        };
    }
}


執行結果: