简体   繁体   English

分配给各种类C#的方法列表

[英]List of methods to assign to various classes C#

I have a sandbox world in Unity with various GameObjects that will eventually have a set of interactions that the player can choose from once they click on this object (best example would be The Sims). 我在Unity中有一个沙箱世界,有各种游戏对象,最终会有一组玩家可以在点击这个对象后选择的交互(最好的例子是模拟人生)。

I basically want each object to contain a list of methods which have been assigned from another list of methods. 我基本上希望每个对象都包含从另一个方法列表中分配的方法列表。 So maybe there is a Tree with the "shake" method, I want to assigned the "shake" method to the Tree's interaction list but the shake method is defined in another class. 所以也许有一个树有“摇动”方法,我想将“摇动”方法分配给树的交互列表,但摇动方法在另一个类中定义。 I also might have a car which could also have the "shake" method. 我也可能有一辆车也可以采用“摇动”方法。

I understand that I can have a list of Action. 我知道我可以列出一个Action列表。

List<Action> interactions = new List<Action>();

and that this list can be populated with methods but Is this the best solution for what I explained above, and can i somehow have a Enum with all possible interactions which would automatically call a particular method for the particular GameObject? 并且这个列表可以用方法填充但是这是我上面解释的最好的解决方案,并且我能以某种方式拥有一个包含所有可能的交互的枚举,它会自动调用特定GameObject的特定方法吗?

I don't know exactly what you're trying to achieve and whether it is the best solution, but to me this sounds like a good use for the strategy pattern: 我不确切地知道你想要实现什么以及它是否是最好的解决方案,但对我来说这听起来像是对战略模式的一个很好的用途:

// This is the 'strategy' in your case
public interface IInteraction
{
    void Do();
}

public class GameObject
{
    // Here is your list of interactions - you can do whatever you want with it.
    public List<IInteraction> Interactions { get; set; }
}

// Here is an interaction
public class Shake : IInteraction
{
    public void Do()
    {
        ....
    }
}

One approach to this would be to have each action defined as a MonoBehavior script of their own. 一种方法是将每个操作定义为自己的MonoBehavior脚本。 Then all you need to do is attach each behavior to each game object as a component. 然后,您需要做的就是将每个行为作为一个组件附加到每个游戏对象。

This would require you changing your pattern of having all the actions defined in another class, but should keep things pretty clean. 这将要求您更改在另一个类中定义的所有操作的模式,但应该保持相当干净。

Then to do each action you could just check if that gameobject has that component and do its action. 然后,要执行每个操作,您只需检查该游戏对象是否具有该组件并执行其操作。 Shake s = gameObject.GetComponent<Shake>();
if(s != null)
{
s.Shake(shakeParameters);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM