- Home /
How to update text every time I press space?
I'm trying to make a dialogue system that goes from one XML sibling to the next until there are no more siblings left.
What I'm stuck on right now is trying to get my text to display the next sibling when I press the space key.
The code I have so far is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Xml;
public class TextPractice : MonoBehaviour
{
Text text;
string XML;
XmlNode currNode;
XmlNode nextNode;
void Start()
{
text = GetComponent<Text>();
XmlDocument doc = new XmlDocument();
doc.Load("Test.xml");
currNode = doc.DocumentElement.FirstChild;
text.text = currNode.InnerText;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
while (nextNode != null)
{
nextNode = currNode.NextSibling;
text.text = nextNode.InnerText;
}
}
}
}
and my XML can be found in the link below:
The issue is that when I press the space key the first sibling of the XML, the one that reads "Hello, how are you?", doesn't change to "O-oh you don't want to talk." which I believe is its sibling node.
I greatly appreciate any help!
Answer by sacredgeometry · Dec 10, 2020 at 07:02 PM
Is there a reason you have chosen XML? Do you need the structure or schema validation? If not maybe there are better formats (just trying to save you time)
There are lots of ways you could do this. but ultimately the fact that its xml shouldn't matter what you want to be doing (providing the xml isnt prohibitively large) is parsing the xml into an in memory data structure like a stack or linked list.
Then you are either grabbing a new item off that stack until there are no more items every time you hit space bar or you are iterating through list until you hit the end of it.
You could also implement it with a method that returns an IEnumerable and yield returns the value.
It really depends on the size of the data and the use case but either way its very similar any way you cut it.
That said why do you need the while loop? wouldnt this be better?
if (Input.GetKeyDown(KeyCode.Space))
{
nextNode = currNode.NextSibling;
text.text = nextNode?.InnerText";
}
Also isnt your xml doc being descoped as you are defining it in your start and then deallocating it once that method invocation ends.
Maybe moving the doc variable onto the class as a class member would help.
Your answer
Follow this Question
Related Questions
UI Text - changing material instance 1 Answer
Unity 4.6 Text Misbehaves During Gameplay 1 Answer
[Solved] UI Text not updating C# 3 Answers
How to edit UI Text from script 3 Answers
Adjusting UI to cellphone screen size 0 Answers