- Home /
C# string replace method
I wanted to replace a certain part of my string into something else. So I started playing with C# strings, and came across the Replace method. So I tried doing it using this:
void DisplayLines(string speakerName, List<string> lines)
{
List<string> newLines;
newLines = lines;
for(int i = 0; i < newLines.Count; i++)
{
if(newLines[i].Contains("<active_char>"))
{
string newLine = newLines[i].Replace("<active_char>", activeChar);
newLines[i] = newLine;
}
}
dialogueDisplay.SetTextToDisplay(newLines);
}
For example, currently my lines is set to "< active_char > is currently speaking", and in the game my active character is named "Elsa". So, it would work for the first time, and would display "Elsa is currently speaking".
However, my variable lines gets replaced as well, it gets overwritten. So the next time I call the same set of lines, the "< active_char >" part has already been replaced by the previous call. So if the active character has now been set to "Anna", it would still display "Elsa". What can I do to avoid this? Or is there another string method that can actually do what I'm trying to do?
Hope I explained it well enough. Thank you for your help!
Answer by Bunny83 · Apr 03, 2016 at 06:27 PM
Here:
newLines = lines;
you don't create a new List but you assign the same list object to the newLines variable. That means whatever you do to newLines will actually affect the list that you've passed into your method. If you want to create a temporary copy of the List you should do:
newLines = new List<string>(lines);
That way you will work on a copy of the list. Whatever you do to that list won't have an effect on the original list.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
A node in a childnode? 1 Answer
how to sort a list of gameobjects? 1 Answer
After Removing everything from the list it backs to 1? 1 Answer