Simple Observer for a Dialogue System Variable

Announcements, support questions, and discussion for the Dialogue System.
Post Reply
Dmangames
Posts: 20
Joined: Fri Jul 13, 2018 9:55 pm

Simple Observer for a Dialogue System Variable

Post by Dmangames »

Hi Tony,

I want to update the number of credits the player has after they purchase something.
Right now I have a text field that loads the number of credits on the scene start, and I would like a simple observer similar to the condition observer but that triggers whenever the dialogue system variable "Credits" changes.

I was looking at the LuaWatchItem class but I'm not too sure how to implement it. Was hoping for some pointers or an example. Thank you!
User avatar
Tony Li
Posts: 22057
Joined: Thu Jul 18, 2013 1:27 pm

Re: Simple Observer for a Dialogue System Variable

Post by Tony Li »

Hi,

How are you changing the Dialogue System variable "Credits"? In a conversation? In a custom script?
Dmangames
Posts: 20
Joined: Fri Jul 13, 2018 9:55 pm

Re: Simple Observer for a Dialogue System Variable

Post by Dmangames »

Hi Tony,

I am accessing Credits though a lua command.

Code: Select all

int value = Lua.Run("return Variable['" + variableName + "']").asInt;

title.text = value.ToString();
The code runs OnEnable. I thought about updating the value on the update loop, but would prefer to do it some other way.
User avatar
Tony Li
Posts: 22057
Joined: Thu Jul 18, 2013 1:27 pm

Re: Simple Observer for a Dialogue System Variable

Post by Tony Li »

Hi,

The DialogueLua class provides an easier way to get variable values:

Code: Select all

int value = DialogueLua.GetVariable("Credits").asInt;
However, a Lua Observer might be easier:

Code: Select all

void OnEnable()
{
    // Initialize text:
    title.text = DialogueLua.GetVariable("Credits").asString;
    
    // Add observer:
    DialogueManager.AddLuaObserver("Variable['Credits']", LuaWatchFrequency.EveryUpdate, OnCreditsChanged);
}

void OnCreditsChanged(LuaWatchItem luaWatchItem, Lua.Result newValue) 
{
    title.text = newValue.asString; // Get .asInt if you want the actual numeric value, too.
}
One or two of these is fine, but they're not ideally efficient because they poll the value every update and then call the function (OnCreditsChanged) if the value has changed. If you need a lot of them, or if you need to squeeze every last nanosecond out of performance, you can register a Lua function. I can describe that process if you need it.
Dmangames
Posts: 20
Joined: Fri Jul 13, 2018 9:55 pm

Re: Simple Observer for a Dialogue System Variable

Post by Dmangames »

Hi Tony,

Thanks for the examples. I ended up using Unity events to call the methods I needed upon buying things.

I didn't know about DialogueLua, I will definitely be using that from now on. Thanks!
Post Reply