I have a question about Custom Variables in C#.

All about user interface, be it customizing built-in UIs or adding new ones.
Post Reply
booksuny
Posts: 47
Joined: 26 Sep 2022 12:37

I have a question about Custom Variables in C#.

Post by booksuny »

I wrote the following code while looking at the manual.

Code: Select all

@set enemy_HP=100
@showUI HPUI

# battle

@hidePrinter
@choice handler:ButtonArea button:MapButtons/Home pos:-300,-300 goto:.attack
@choice handler:ButtonArea button:MapButtons/Shop pos:300,200 goto:.defend
@stop

# attack
PC: attack!
@set enemy_HP-=10
@goto .battle

# defend
defend!
@goto .battle

@stop

The following code was written to utilize 'enemy_HP' in C#.

Code: Select all

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Naninovel;

public class HP_Bar : MonoBehaviour {

void Update()
{
    var variableManager = Engine.GetService<ICustomVariableManager>();

    variableManager.TryGetVariableValue<int>("enemy_HP", out var intValue);

    enemy_HP = 55;
    variableManager.TrySetVariableValue("enemy_HP", intValue);        
}
}

However, the following error occurs:
The name 'enemy_HP' does not exist in the current context

I think I wrote it as it is while looking at the manual, is there anything I made a mistake?

idaot
support
Posts: 262
Joined: 01 Aug 2020 08:25

Re: I have a question about Custom Variables in C#.

Post by idaot »

Do not use Update() unless you are working with a feature that necessitates it like input processing. Right now you are basically trying to access a custom variable at every frame that may not have existed before using @set. Instead of Update(), use one of the events found in the Naninovel codebase that fits your use case the best. https://naninovel.com/guide/engine-serv ... -services

Post Reply