- Home /
Event-based spawning
Hi!
This is really an architecture / pattern issue... don't know where it belongs. I hope it's not misplaced or a "what kind of ice cream do you like"-type question. If so, please feel free to ignore me =)
I'm trying to set up an event-based spawning of various objects, and I'm looking for a clean way to do it. I have a class (non-MonoBehaviour) that holds the 'blueprint' for the object to be spawned. I have lots of instances of that class, so I like that it is NOT a MonoBehaviour, 'cause it keeps it clean (should use a struct, maybe...). Then I want the game engine to fire events, carrying the game state (an int called 'height'), triggering callbacks to instantiate based on the blueprint.
My challenge is to do this in a clean way. Right now I'm nestling the classes in a kind of ugly way, which I would like to avoid if possible.
So: can I do this in a way that keeps the ObstacleSpec ('blueprint') class free from any logic, thus separating creation from blueprint? Or is this code actually fine, I'm I just whining?
The code works, it's just that I feel it could be done alot better. I do kind of understand events and delegates and that stuff, but I'm hardly a pro... Any thoughts greatly appreciated!
My code is (basically):
public delegate void EntryEventHandler(int height);
public class LevelBehaviour : MonoBehaviour {
...
public event EntryEventHandler Entry;
protected virtual void OnEntry(int height) {
if (Entry != null) {
Entry(height);
}
}
//This is called from a game engine singleton, at the appropriate occasions... No trouble here
public void performLevelActions(int currentHeight) {
OnEntry(currentHeight);
}
public void Spawn(ObstacleSpec os) {
Instantiate... etc, i.e. MonoBehaviour-based operations, and set stuff based on information in blueprint
}
}
public class ObstacleSpec {
LevelBehaviour levelBehaviour;
int entryHeight;
//various other properties
public ObstacleSpec(LevelBehaviour levelBehaviour, int entryHeight, ...) {
this.levelBehaviour = levelBehaviour;
this.entryHeight = entryHeight;
this. ... = ...;
//Subscribe to the listener, REALLY want to avoid referencing LevelBehaviour from inside ObstacleSpec!
levelBehaviour.Entry += new EntryEventHandler(PerformEntry);
}
//REALLY want to avoid referencing LevelBehaviour from inside ObstacleSpec! Can I move this outside, somehow?
void PerformEntry(int height) {
if(height == entryHeight) {
levelBehaviour.Spawn(this);
}
}
}
Answer by Berenger · May 03, 2012 at 03:47 AM
You could try this method to send a message to LevelBehaviour without referencing it, or else use a singleton for LevelBehaviour.
Your answer
Follow this Question
Related Questions
Make a event happen every 4 seconds? 1 Answer
Question about spawning enemies 1 Answer
Instantiate Prefabs on "Grid" Pattern? 1 Answer
Architecture for a network game- problems with events 0 Answers
UnityEditor on Tag Update event 0 Answers