Strategy Pattern with Monobehaviours

Is there a trick to using the strategy pattern with Monobehaviours? Say you have an interface the Monobehaviour uses. Can you pick an implementation of that interface at run-time and use that?

The best I could come up with was to create a non-MonoBehaviour interface and set of classes which implement the strategy pattern and pass those into the MonoBehaviour when I “construct it” by calling an Initialize method in a Factory class after my Instantiate calls to instantiate the Prefab. This works kind of well, but inside the class you don’t have access to the gameObject’s variables the the same way a Monobehaviour can just grab them as instance variables.

If you had shown some code I would have had a lot more to go on, but I would think you currently have the interface as a class variable in a MonoBehaviour, yet you need access to e.g. transform or rigidbody from within that implementation of the interface.

The way I would implement the Strategy pattern in Unity is to create a MonoBehaviour of each implementation, then add those to the GameObject after you’ve decided on which strategy needs to be used. Depending on your use case, the strategy can then be removed after it having served its purpose and a new one added as need be.

GetComponent doesn’t really play nice with interfaces, so I use this piece of code to determine if any Component in a GameObject implements an interface:

	public static void GetInterfaces<T>(out List<T> resultList, GameObject objectToSearch) where T: class {
		MonoBehaviour[] list = objectToSearch.GetComponents<MonoBehaviour>();
		resultList = new List<T>();
		foreach(MonoBehaviour mb in list){
			if(mb is T){
				//found one
				resultList.Add((T)((System.Object)mb));
			}
		}
	}

Though it is rather cubersome so I usually try to avoid using interfaces when dealing with MonoBehaviours. I use interface-like abstract classes with deep inheritance so I can use GetComponent. Haven’t run into maintenance problems… yet.

I have to admit I’m not sure I quite understand the problem, but maybe you would find this useful:
http://www.gamasutra.com/blogs/VictorBarcelo/20131217/207204/Using_abstractions_and_interfaces_with_Unity3D.php

It is what I’m using atm to switch implementations at runtime.

You may also want to invest in something like the Full Inspector from the Asset Store, which gives you editor support for interfaces, something that you don’t get from vanilla Unity: https://www.assetstore.unity3d.com/#/content/14913