Calling functions during Dialogue
It’s one thing just making some words appear on the screen, but wouldn’t it be nice if your dialogue did a little more than just show text? Well, with a little bit of function mapping, you can call functions from strings stored in your JSON file! This example is just going to use a simple function to move an object while an NPC is speaking, but the principle could be applied to all sorts of things.
The NPC spawns this emote after about three lines of dialogue, it clearly likes the player!
The first thing to do is to create the function we’re going to call. All we’re going to do with this demo is move our Heart object to above the NPC associated with this line of dialogue (the middle one), so the function is called HeartDemo:
On function HeartDemo
Heart ▶︎ Set position to (288, 32)
System ▶︎ Wait 2 seconds
Heart ▶︎ Destroy
Now that we’ve created the function, we need to map it to a specific string. This will be added as an action to the On Start of Layout event at the top of the event sheet:
Condition
System ▶︎ On Start of Layout
Action
Functions ▶︎ Map “JSONFunctions” string “MoveHeart” to HeartDemo
In this action, JSONFunctions is the name of the function map we’ll be using (you can have multiple function maps in a project) and the string MoveHeart is the string that is stored in the JSON to identify the function. We’re now assigning that string to the HeartDemo function.
Now that we’ve mapped our demo function, we need to add in the functionality to be able to call that function during the dialogue. The first thing needed to do this is another new function.
The DisplayFunction function is far simpler than the one we use to show dialogue, in fact it could be whittled down to just a single action if you prefer:
On function DisplayFunction
Number Parameter: dialogueID
Number Parameter: sceneID
Action
System ▶︎ Set layer “Dialogue” invisible
Functions ▶︎ Call function from “JSONFunctions” map with string JSON.Get(“scene.” & curScene & “.dialogs.” & curDialogue & “.function”)
When you add in the action to call the function, the dialog will have a box for Forward parameters, but you don’t need to worry about that in this case, leave it as zero.
So that’s the function that will call whichever function it finds in the JSON file, but we need to call the DisplayFunction function! To do this, a sub-event will be added to the event block where we call DisplayLine, that’s event 11 in the example project.
There’s already a sub-event for calling the DisplayLine function so the easiest thing to do is create a copy of that sub-event. Then, where the event says JSON key = “line”, change the word line to function. Then change the action to call DisplayFunction instead of DisplayLine. You should end up with this:
Now you have the events, you can create new functions, add them to the function map and add their strings to your JSON dialogue file. Just remember to make sure their type is defined as "function" in the JSON file!