Call and save an inherited abstract class into a variable

I need a variable, which will hold instance to a class. There are about 10 such classes, all inherit from single abstract script. In my general processing I need to able to use create new instances as well as store current instance, however they’re all seperate classes but they do inherit from the same script. Is there a way to store a script by the class it is abstracted from? After all, the method and variables correlation are guaranteed. The point is that an IEnumerator does its execution, until something is changed, this IEnumerator then needs to stop, and another one will be invoked, for this, I need to store the class. Note that in reality the classes are much more complex, I cannot just store IEnumerator, I need whole class.

Here’s a pseudocode to give you an idea:

Start with:
Manager.WhenSomething(Class1);
then:
Manager.WhenSomething(Class2);

public abstract class ToInherit {
    public abstract IEnumerator Function1();
}

public class Class1 : ToInherit
{
    public override IEnumerator Function1() {
        // does something 1
    }
}

public class Class2 : ToInherit
{
    public override IEnumerator Function1() {
        // does something 2
    }
}


public static class Manager {

    //public ToInherit current ????

    // WhenSomething(Class2) ????
    public void WhenSomethingChange(ToInherit newItem) {
        StopCoroutine(current.Function1);
        current = new typeof(newItem);  // ????
        StartCoroutine(current.Function1);
        // Effectively: StartCoroutine(Class2.Function1);
    }

}

You’re like 90% of the way there…

public static class Manager {
    public ToInherit current;
    Coroutine currentlyRunningCoroutine;

    public void WhenSomethingChange(ToInherit newItem) {
        if (currentlyRunningCoroutine != null) {
            StopCoroutine(currentlyRunningCoroutine);
        }

        current = newItem;
        currentlyRunningCoroutine = StartCoroutine(newItem.Function1());
    }
}
1 Like