Sunday, February 7, 2016

Open, Sesame!

Just implemented the switch mechanic.

Main problem: how do you make objects interact with / control other objects, in a Unity-idiomic way? My first thought was to just make a new script file for every interactable object, and just have a few hundred C# files named like "map03_switch24.cs". Clearly an amazing and elegant solution.

Then I thought about the different types of objects I planned on making. Fortunately, there are only a couple of types of them, like doors, switches, lights, sensors... And most of them work in the same way: switches just switch a couple objects on or off, doors can be opened or closed, etc.

So what if I just create a couple of components, like Door, Lamp, etc.? Then each will have an "OnSwitch" function, which will cause some change (for example, the door will open).

Last time, I've implemented the Selectable component. I have made two additions:
1. Each selectable now have a list of objects assigned to it (that it can manipulate)
2. Added a little clause to the code: if a selectable object is selected, and the player presses the "Jump" key (spacebar), then it calls "OnSwitch" on all the assigned objects.

The only problem is how to get the component of the objects. I mean, I could just look for all the Door, Lamp, etc. components, but it would be error prone. Fortunately, one can make Interfaces in Unity. So I just created an ISwitchable interface, with one function, OnSwitch(), and then went on the components, and told Unity that they implement this interface.

After that, I could write GetComponent<ISwitchable>().OnSwitch(), and it worked. Ez-pz.

Now, a few words about doors: I plan to have traditional doors in the beginning (when you open it, it turns around the hinges), but later on, I might want sliding doors, or doors that just go transparent. So I created a few kinds, which one can select in the inspector.

(Gif in full post)


AND NOW THE OBLIGATORY GIF:



No comments:

Post a Comment