【问题标题】:Calling a method that is unspecified at compile time调用编译时未指定的方法
【发布时间】:2014-08-09 01:59:15
【问题描述】:

在 Unity 中进行修补,我的 GUI 的一部分将呈现来自代表游戏中不同事物的几种不同类类型之一的信息(例如敌人统计数据)。所有不同的类都有一个方法来创建一个包含所需信息的信息对象(例如enemyInfoObject),它有一个 DrawInfo() 方法,可以根据游戏对象绘制信息。

在我的信息渲染脚本中,我希望能够将任何一个不同的信息对象分配给单个变量(即当前选择的敌人、NPC 等)并能够调用 DrawInfo() 方法.有没有一种干净、简单和/或更好的方法来做到这一点?

如果需要,我可以详细说明。

【问题讨论】:

  • 使用界面? (interface {void DrawInfo();})

标签: c# unity3d


【解决方案1】:

这是一种众所周知的设计模式,称为"Strategy Pattern"。它扩展了“编程到接口”的思想。

策略模式旨在提供一种定义家庭的方法 算法,将每一个封装为一个对象,并使其 可互换。策略模式让算法变化 独立于使用它们的客户。

首先,定义一个包含DrawInfo的接口,比如ISprite。你所有的精灵都是实现这个接口的类。现在游戏可以存储对选定ISprite 的引用并对其调用方法。

例如:

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();
        }
    }
}

【讨论】:

  • 感谢您的建议 - C# 中的接口对我来说是新的。我想问一下,接口位是否可以从 Unity 中的单独 C# 脚本继承,但经过一些测试,它们似乎是。
【解决方案2】:

我能想到的最好方法是让游戏中所有你想调用 DrawInfo() 的对象都实现一个接口,比如IDrawableInfo

IDrawableInfo.cs

public interface IDrawableInfo
{
    void DrawInfo();
}

EnemyInfoObject.cs

public class EnemyInfoObject : IDrawableInfo
{
    public void DrawInfo()
    {
        // Do drawing stuff here
    }
}

YourScript.cs

if(objectIdLikeToDrawInfoFor is IDrawableInfo)
{
    objectIdLikeToDrawInfoFor.DrawInfo();
}

您可以通过将 DrawInfo() 调用包装在这样的 if 语句中来避免运行时错误。

【讨论】:

  • 感谢您的信息。我是否可以将多个答案设置为已接受。
  • 没问题。您应该始终接受最适合您的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
相关资源
最近更新 更多