- Home /
Function with a variable text in the middle of it
Is there a way to have a variable in the middle of a function? Say I have the following code:
switch (citizen.Name) {
case ("Tom"):
text = DialogueManager.GetTomDialogueCasual();
break;
case ("John"):
text = DialogueManager.GetJohnDialogueCasual();
break;
}
If I had several different characters, I would have to have a massive switch function where every case is very similar to each other. Is there a way to simplify it? Something along the lines of
text = DialogueManager.Get{citizen.Name}DialogueCasual();
What is the situation you're trying to avoid by not just passing in a variable? Are you trying to have slightly different logic for each of those (in which case you'd need slightly different function bodies anyway)?
In this case, the characters would have different lines of dialogue. Thus, there would be a lot of typing if I had to make a switch-case for every character. Ins$$anonymous$$d, I'd like to replace the whole switch-case with that single line.
Answer by Deathdefy · Oct 18, 2018 at 02:32 PM
This can be accomplished with either a list or dictionary. All you need to do is populate them prior to(you could populate a list in the inspector if you wanted to but not a dictionary). In this example I used linq to query out what person I need.
using System.Linq;
public class Person
{
public string Name;
public string Dialogue;
}
public class MyClass: MonoBehaviour
{
private List<Person> myPeople = new List<Person>();
private void Start()
{
Person p1 = new Person();
p1.Name = "Tom";
p1.Dialogue = "Test Dialogue";
myPeople.Add(p1);
}
public void UpdateDialogText(Person person)
{
//however you are getting your text
Text myText = GetComponent<Text>();
myText.text = myPeople.First(x => x.Name == person.Name).Dialogue;
}
}
That will throw a System.InvalidOperationException exception if a match isn't found. Consider changing that to either FirstOrDefault
(which will at least give you a null
to check for) or adding a try/catch block.