Search Unity

Serializing and deserializing event listener connections?

Discussion in 'Scripting' started by eses, Jan 19, 2019.

  1. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Think lever/switch that is connected to some listener like a door, that opens when someone pulls a lever. I was playing around with adventure/dungeon crawler kind of thing and was thinking about how to build levels from data. I would do following;

    1. Load all level data from file JSON (persisting object states for level state saving/loading would be the same)
    2. Build the level from this data using prefabs.
    3. Do another pass. Create lever/switch/trigger connections and such based on JSON data.

    I can't just drop a listener method somewhere in inspector as I don't have objects in scene as these would be created run-time. All I could think of, is to store (unique)name/id of object that listens to some specific event, then serialize/deserialize that information.

    This is what I came up with after testing - after loading level data:
    1. Process and create all levers from level/save data (among other objects)
    2. For each lever, process it's connections.
    3. Do find for target object of lever connection *
    4. If target is found, get the listener component.
    5. Then get the actual method that should be listening to event and assign it to lever connection's own event.

    * = Maybe I could put all levers/switches to some dictionary (leverID, leverObject) when loading, then do the connecting after.

    I would like to limit serialization to JSONUtility, as that is what I like to use to keep things simple for myself. I'm learning this stuff slowly, so I try to not complicate things, to be able to concentrate on gameplay related stuff. Using unique names might be good enough for this, as the levels would be pretty much static (no new levers and triggers created)



    Maybe there is better approach than this?

    Using unique names sounds like asking problems, yet I think it would be enough for this.

    Then again, I don't know how to serialize delegate methods assigned to lever connection's event. I don't think that's even possible, at leasth with JsonUtility. I couldn't find any articles on similar topic, neither on Stackoverflow (probably wrong keywords).
     
    Deleted User likes this.