c# - 使用字典进行散列
问题描述
我正在为我在课堂上做的一个小型统一游戏做一项特定的任务。在其中,我试图散列一个包含变量的类和一个特定于为字典创建的每个类的方法。这些变量可以正常工作,因为它们不需要是静态的并且不是抽象的,但是我正在努力使用的方法。
这是我正在使用的整个脚本。
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
函数被覆盖和可调用。我将如何设置这个类/方法的字典,一旦它被正确添加到字典中,我将如何调用它?
解决方案
我认为你正在接近你的类结构和错误地覆盖你的抽象方法的方法,这导致了字典的混乱。
我将为敌人创建一个界面,定义你的敌人需要包含和执行的内容。然后,您可以创建一个抽象基类,为敌人实现通用功能。然后,每种敌人类型都应该从您的基类继承。
请参见下面的示例:
// 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");
}
}
推荐阅读
- node.js - 使用 opensubtitles API 在 NodeJS 上下载文件
- sql - SQL查询比较表之间的行之间的差异
- listview - Xamarin 中列表视图和网格行高的 DynamicResource 样式
- python - 烧瓶类型错误:__init__() 缺少 1 个必需的位置参数:“状态”
- javascript - 从 API 数据切换 Div 隐藏/显示
- python - 基于索引对多索引数据执行操作
- react-router-v4 - 使用 React BrowserRouter (v4) 如何识别位置何时发生变化?
- java - 为 Android 游戏使用 Aync 任务
- javascript - 删除包含特定文本的链接
- java - 如何将 Maven 清单添加到指定依赖项的 AAR