You shall seek and always find with this generic seeker type pattern

Imagine you have a bunch of popup templates that you want to use across a codebase.

You have a bunch of prefabs for those popups.

You can use the logic I’m about to describe to do stuff like:

Popup.Find<YourPizzaIsReadyPopup>().Show()

Disclaimer: Don’t overuse this or you’ll have spaghetti code.

Ok, let’s go, I called this the seeker pattern, because it helps you find stuff.
Have a better name? Cool, keep it to yourself.

public static class SeekableExtensions
{
    public static bool IsOfSeekableType<T>( this Seekable seekable ) where T : Seekable
    {
        return seekable.GetType() == typeof(T);
    }
}
 
public interface Seekable
{
    void Seek();
}
 
public class UnassumingBystander : Seekable
{
    public void Seek()
    {
        Debug.Log( "Oh, you found me..." );
    }
}
 
internal class SeekableNotFoundException : Exception
{
}
 
// A wizard is a singleton
public class Wizard
{
    List<Seekable> seekables;
 
    T GetSeekable<T>() where T : Seekable
    {
        foreach ( var arcanizer in seekables )
        {
            if ( arcanizer.IsOfSeekableType<T>() )
            {
                return (T)arcanizer;
            }
        }
        throw new SeekableNotFoundException();
    }
 
 
    void DoStuff()
    {
        GetSeekable<UnassumingBystander>().Seek();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *