- Home /
How to transform a string into a variable in a dialogue
Hello,
I am making a simple dialogue system, and would like to "dynamise" some of the sentences. For exemple, I have a Sentence
Hey Adventurer {{PlayerName}} ! Welcome in the world !
Now In code I am trying to replace that by the real value of the string in my game. I am doing something like this. But it doesn't work. I do have a string PlayerName
in my component where the function is situated
Regex regex = new Regex("(?<={{)(.*?)(?=}})");
MatchCollection matches = regex.Matches(sentence);
for(int i = 0; i < matches.Count; i++)
{
Debug.Log(matches[i]);
sentence.Replace("{{"+matches[i]+"}}", this.GetType().GetField(matches[i].ToString()).GetValue(this) as string);
}
return sentence;
But this return me an error, even tho the match is correct.
Any idea of a way to do it ?
Answer by rossadamsm · Dec 16, 2018 at 08:03 AM
@Popolee This seems a little bit of a complicated way to replace strings (but I am assuming it makes more sense in the general dialog system you would like to create.)
I don't get any errors when I run your code however I wasn't getting the expected result because of one small oversight. You are not assigning the replaced sentence back into the sentence variable before returning it. That is , you need
sentence = sentence.Replace("{{" + matches[i] + "}}", this.GetType().GetField(matches[i].ToString()).GetValue(this) as string);
Hope that solves your problem!
yes thanks, I notice after posting. Then I must have a problem somewhere else. Will check on it
Answer by Popolee · Dec 16, 2018 at 08:15 AM
Oh, the variable must be Public... !
Yes, if you using reflection it will only be public variables by default. However you can specify the binding flags to find private properties too.
System.Reflection.BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic;
sentence = sentence.Replace("{{" + matches[i] + "}}", this.GetType().GetField(matches[i].ToString(),flags).GetValue(this) as string);
Your answer
Follow this Question
Related Questions
Modifying Brackeys' dialogue system for questions/different dialogue "paths"? 1 Answer
Problems with simple dialogue 0 Answers
How to make a text appear gradually? 0 Answers
Game slows down when printing text 1 Answer
Dialogue & GUI Text String 1 Answer