首页 > 解决方案 > 使用字典进行散列

问题描述

我正在为我在课堂上做的一个小型统一游戏做一项特定的任务。在其中,我试图散列一个包含变量的类和一个特定于为字典创建的每个类的方法。这些变量可以正常工作,因为它们不需要是静态的并且不是抽象的,但是我正在努力使用的方法。

这是我正在使用的整个脚本。

using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class EnemyZ : MonoBehaviour
{
    // Class used to hash names health assets and then move options
    public class EnemySet
    {
        public string EnemyName { get; set; }
        public float EnemyHealth { get; set; }
        public void Moves()
        {

        }
    }

    //setting EnemySet with names health (assets and move options)
    public static void Setup()
    {
        var cards = new Dictionary<string, EnemySet>()
        {
            { "Slime", new EnemySet { EnemyName="Slime", EnemyHealth= 25} },
            { "Flaz", new EnemySet { EnemyName="Flaz", EnemyHealth= 34} },
            { "BandShee", new EnemySet { EnemyName="BandShee", EnemyHealth= 45} },
            {"Fan-Natic", new EnemySet{EnemyName = "Fan-Natic", EnemyHealth = 20} }
        };
    }

    void Update()
    {

    }
}

我希望该Move函数被覆盖和可调用。我将如何设置这个类/方法的字典,一旦它被正确添加到字典中,我将如何调用它?

标签: c#dictionaryunity3d

解决方案


我认为你正在接近你的类结构和错误地覆盖你的抽象方法的方法,这导致了字典的混乱。

我将为敌人创建一个界面,定义你的敌人需要包含和执行的内容。然后,您可以创建一个抽象基类,为敌人实现通用功能。然后,每种敌人类型都应该从您的基类继承。

请参见下面的示例:

// all enemy types must implement the following
public interface IEnemy {
    string EnemyName { get; }
    float EnemyHealth { get; }
    void Move ();
}

// abstract base class for common functionality
public abstract class Enemy : IEnemy {
    protected float speed = 0.1f;

    public string EnemyName { get; protected set; }
    public float EnemyHealth { get; protected set; }

    public virtual void Move () {
        Debug.Log ($"{EnemyName} moving at {speed}");
    }
}

public class Slime : Enemy {
    public Slime () {
        speed = 0.1f;
        EnemyName = "Slimer";
        EnemyHealth = 100f;
    }

    public override void Move () {
        Debug.Log ($"{EnemyName} moving at {speed}");
    }
}

public class Flaz : Enemy {
    public Flaz () {
        speed = 0.5f;
        EnemyName = "Flaz";
        EnemyHealth = 50f;
    }

    public override void Move () {
        Debug.Log ($"{EnemyName} moving at {speed}");
    }
}

public class Test : MonoBehaviour {
    readonly List<IEnemy> Enemies = new List<IEnemy> ();

    void Start () {
        var slimer = new Slime ();
        Debug.Log ($"{slimer.EnemyName} initialized with health of {slimer.EnemyHealth}");
        slimer.Move ();

        var flaz = new Flaz ();
        Debug.Log ($"{flaz.EnemyName} initialized with health of {flaz.EnemyHealth}");
        flaz.Move ();

        Enemies.Add (slimer);
        Enemies.Add (flaz);

        Debug.Log ($"Added {Enemies.Count} enemies");
    }
}

推荐阅读