调用在编译时未指定的方法 [英] Calling a method that is unspecified at compile time
问题描述
在Unity中修修补补,我的GUI的一部分将呈现来自代表游戏中不同事物的几种不同类类型之一的信息(例如,敌方状态).所有不同的类都有一个用于创建包含所需信息的信息对象的方法(例如敌人信息对象),该方法具有一个DrawInfo()方法,该方法根据游戏对象绘制信息.
Tinkering in Unity, I have a part of my GUI that will render information (e.g. enemy stats) from one of several different class types representing different things in the game. All of the different classes have a method for creating an information object that contains the desired information (e.g. enemyInfoObject), which have a DrawInfo() method that draws the info depending on the gameObject.
在我的信息呈现脚本中,我希望能够将任何一个不同的信息对象分配给一个变量(即当前选择的敌人,NPC等),并能够调用DrawInfo()方法.有没有一种干净,简单和/或更好的方法来做到这一点?
In my information-rendering script I would like to be able to assign any one of the different information objects to a single variable (i.e. the currently selected enemy, NPC, etc.) and be able to call the DrawInfo() method. Is there a clean, simple, and/or better way to do this?
如有需要,我可以详细说明.
I can elaborate if needed.
推荐答案
这是一种众所周知的设计模式,称为.它扩展了编程到接口"的思想.
This is a well-known design pattern called the "Strategy Pattern". It extends the idea of "programming to an interface".
该策略模式旨在提供一种定义家庭的方式 的算法,将每个算法封装为一个对象,并使它们 可互换的.策略模式使算法有所不同 独立于使用它们的客户.
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
首先,定义一个包含DrawInfo
的接口,例如ISprite
.您所有的Sprite都是实现此接口的类.现在,游戏可以存储对所选ISprite
的引用,并在其上调用方法.
First, define an interface containing DrawInfo
,say ISprite
. All your sprites will be classes that implement this interface. Now the game can store a reference to the selected ISprite
and call the method on it.
例如:
public interface ISprite
{
void Draw();
}
public class BossMonster : ISprite
{
public override void Draw()
{
// Draw scary stuff
}
}
public class NPC : ISprite
{
public override void Draw()
{
// Draw stuff
}
}
public class Game
{
private ISprite currentSprite = ...
private List<ISprite> otherSprites = ...
public void Render()
{
currentSprite.Draw();
foreach (ISprite sprite in otherSprites)
{
sprite.Draw();
}
}
}
这篇关于调用在编译时未指定的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!