简体   繁体   中英

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).

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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