- Home /
How to get an input and put it into a scriptable object?
I'm trying to make a game where players input their names and they get random questions. For an example if the player inputs a name "John", the question will be "John have you ever done bla bla". So I'm wondering if there's a way to get the input from 1 script, and then in ScritableObject script, assign that input to a string or when i create the asset of that ScriptableObject be able to decide at what part of the string does the name from an input appear. My question might be confusing, so basically is there a way to use string interpolation in scriptable objects?
Answer by Hellium · Apr 20 at 02:42 PM
Why not simply use string formatting?
[SerializeField]
private string[] questions = new string[]
{
"Hello {0}!",
"{0} have you ever done bla bla"
};
// To be set from the input's value
public string Interlocutor { get; set; }
public string GetQuestion(int index)
{
return string.Format(questions[index], Interlocutor);
}
You may have questions with other inputs, so you'll need a more custom solution using a simple Replace for instance.
[SerializeField]
private string[] questions = new string[]
{
"Hello {{interlocutor}}!",
"{{interlocutor}} have you ever {{action}}",
"You have {{coins}} coins",
};
// To be set from the input's value
public string Interlocutor { get; set; }
public string Action { get; set; }
public int Coins { get; set; }
public string GetQuestion(int index)
{
var sb = new StringBuilder(questions[index]);
sb.Replace("{{interlocutor}}", Interlocutor);
sb.Replace("{{action}}", Action);
sb.Replace("{{coins}}", Coins);
return sb.ToString();
}
I thought about this and im literally making this right now, but the problem is, what if later i have lets say 200 questions, is it a good idea to write it all like this? The code would look too big and ugly.
Your questions will be set in the inspector. Here, I did it in code for the sake of the example.
You could also have a Dictionary to set the input instead of fields.
private Dictionary<string, string> parameters = new Dictionary<string, string>();
public void SetParameter(string key, string value)
{
parameters[key] = value;
}
public string GetQuestion(int index)
{
var sb = new StringBuilder(questions[index]);
foreach(var parameter in parameters)
sb.Replace(parameter.Key, parameter.Value);
return sb.ToString();
}
You are right, thank you, btw when writing strings in inspector because of [SerializeField], if I write lets say:
{{playerName}} take 3 sips
it will drag the playerName variable out of the script and attach it to the string?
Your answer
Follow this Question
Related Questions
Inputfield set as Variable 1 Answer
Getting the text from UIInput 1 Answer
Unity mobile keyboard like "WhatsApp" 0 Answers
Half of InputField unresponsive 1 Answer
How to schedule responses (based on player's input text) for text adventure game? 0 Answers