Child of child of MonoBehaviour isn't a MonoBehaviour?
I've found a way around this problem, but it's a curious issue that I'd still like to know the answer to.
I'm authoring unit tests for a non-MonoBehaviour class that uses a singleton MonoBehaviour, Updater, that I've written to send Update events to non-MonoBehaviours that need them. I have one such class that registers for these events in its constructor, so that callers don't need to worry about registering it.
For unit tests, though, I'm triggering these Update events manually, so I only need an UpdaterDummy, a child of Updater that hides the actual behavior. In test setup, I need to set my singleton, as:
public class Updater : MonoBehaviour {
protected static Updater Instance; // With getters, etc.
[...] // Has an Initialize method to set the Instance.
}
public class UpdaterDummy : Updater {
[...] // Hides Initialize with a new implementation to set the Instance to a dummy.
}
[TestFixtureSetUp]
public void Setup() {
UnityEngine.GameObject gameObject = new UnityEngine.GameObject("test");
unitTest.UpdaterDummy updater = gameObject.AddComponent<unitTest.UpdaterDummy>();
updater.Initialize(); // Sets the singleton instance.
}
Edit: The Updater and UpdaterDummy are in their own files with the appropriate names.
However, this fails with Unity's The script needs to derive from MonoBehaviour!
error at AddComponent, despite the fact that UpdaterDummy is an Updater, which is a MonoBehaviour. Curiously, if I replace that with:
unitTest.UpdaterDummy updater = new unitTest.UpdaterDummy();
then I get the You are trying to create a MonoBehaviour using the 'new' keyword
error at runtime, but the code runs as expected.
So Unity knows that this is a MonoBehaviour, but AddComponent returns null because it's not a MonoBehaviour? I've tried various combinations of hiding and overriding members in UpdaterDummy, but even when UpdaterDummy inherits Updater verbatim, I still hit these errors. I'm assuming this is some issue with inheritance with children of MonoBehaviours, but I guess that's why I'm asking! Thanks.
$$anonymous$$y guess here is Unity does not allow $$anonymous$$onoBehaviours to be added as components if their file name is different. place em into separate classes and I bet it works. The inspector needs to know what to show here.
Ah, to clarify, the Updater classes are indeed each in their own file with the appropriate name.