首页 文章

在C#中使用抽象变量和非抽象方法创建超类

提问于
浏览
0

基本上,超类应该包含将在子类中设置的变量(或属性,无论哪个工作),并且还应包含所有子类将使用的方法 . 我不知道是否有办法在不使用2个类的情况下执行此操作,一个是包含变量的接口,另一个包含方法的类,但我认为有 . 你可能想象我对C#很陌生 .

只是为了澄清,这是针对Unity中的项目而且超类将是所有子类(字符)将使用的通用字符类 .

编辑:稍后将添加许多其他变量和方法,但这里是粗略预览它应该是什么

using UnityEngine;
using System.Collections;

public abstract class CharacterClass : MonoBehaviour {

    int MaxHitPoints { get; set; }
    int ArmorRating { get; set; }
    int Speed { get; set; }
    int Strength { get; set; }
    int Agility { get; set; }

    void changeHP(int change)
    {
        MaxHitPoints += change;
    }

}

2 回答

  • 2

    超类将是一般字符类

    ?但等等,真的没有这样的事情--Unity是一个ECS系统 .

    您所能做的就是将组件添加到 GameObject . (也就是说,行为 - 所有你能做的就是添加行为(渲染器,骨骼动画师,计时器,相机,碰撞器,等等)到 GameObject s

    在Unity中没有继承或类似继承的东西; OO甚至都不含糊 . 使用Unity就像使用Photoshop一样!

    (当然,在编写时,恰好在编写时使用的语言,在Unity中编写组件是一种OO语言,但是's irrelevant, could change tomorrow. That doesn'以任何方式使Unity成为OO . )

  • 0

    面向对象的编程概念在Unity中仍然可用于从组件构建实体 .

    using UnityEngine;
    
    public abstract class Character : MonoBehaviour
    {
        public int HitPoints { get; set; }
    
        public virtual void ChangeHP(int amount)
        {
            HitPoints += amount;
        }
    
        void OnCollisionEnter(Collision other)
        {
            if (other.gameObject.CompareTag("DeathTrigger"))
            {
                Die();
            }
        }
    
        protected virtual void Die()
        {
            Debug.Log("I'm dead.");
        }
    }
    
    public class LordOfTerror : Character
    {
        protected override void Die()
        {
            base.Die();
            Debug.Log("But I also come back from the dead very soon.");
            HitPoints = 100;
        }
    }
    

    但是,这种编程确实只适用于小型继承树,并且只有一些限制或变通方法才能在Unity中习惯 . 通常,尽可能多地使用组件是有意义的 . 以下是示例中的变体,展示了如何将面向对象与组合结合起来:

    using System;
    using UnityEngine;
    
    public abstract class StatAttribute
    {
        public int current;
        public int min;
        public int max;
    
        public void Change(int amount)
        {
            current += amount;
        }
    }
    
    public sealed class Health : StatAttribute
    {
        public event Action tookDamage;
    
        public bool isAlive
        {
            get { return current > min; }
        }
    
        public void Damage(int amount)
        {
            base.Change(-amount);
            // also fire an event to make other components play an animation etc.
            if(tookDamage != null)
                tookDamage();
        }
    }
    
    public sealed class Speed : StatAttribute
    {
        public int boost;
    
        public int GetFinalSpeed()
        {
            return base.current * boost;
        }
    }
    

    通常,您从附加到GameObjects的各个组件开始 . 所有组合构成了你的角色 . 你有Health,CharacterMovement,PlayerInput,Animation等等 . 在某些时候你注意到代码是重复的,这是在组件之间共享某些基类可能有意义的地方 .

相关问题