Skip to content

Instantly share code, notes, and snippets.

@digiwombat
Last active July 25, 2021 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digiwombat/472b3bbb936f49502460969a51e5421c to your computer and use it in GitHub Desktop.
Save digiwombat/472b3bbb936f49502460969a51e5421c to your computer and use it in GitHub Desktop.
public class DialogueParserExample : MonoBehaviour
{
public static string FilterText(string text)
{
const string genderStartTag = "[g=";
const int maxReplacements = 100;
if (text.Contains(genderStartTag))
{
Regex regex = new Regex(@"\[g=[^\]]*\]");
int endPosition = text.Length - 1;
int numReplacements = 0; // Sanity check to prevent infinite loops.
while ((endPosition >= 0) && (numReplacements < maxReplacements))
{
numReplacements++;
int genderTagPosition = text.LastIndexOf(genderStartTag, endPosition, System.StringComparison.OrdinalIgnoreCase);
endPosition = genderTagPosition - 1;
if (genderTagPosition >= 0)
{
string firstPart = text.Substring(0, genderTagPosition);
string secondPart = text.Substring(genderTagPosition);
string secondPartVarReplaced = regex.Replace(secondPart, (Match match) =>
{
//Debug.Log(match.Value);
string genderText = match.Value.Substring(3, match.Value.Length - 4).Trim(); // Remove "[var=" and "]"
try
{
return GameData.Instance.playerGender == "Male" ? genderText.Split('/')[0] : genderText.Split('/')[1];
}
catch (System.Exception)
{
if (DialogueDebug.logWarnings) Debug.LogWarning(string.Format("{0}: Failed to get gender text: '{1}'", new System.Object[] { DialogueDebug.Prefix, genderText }));
return string.Empty;
}
});
text = firstPart + secondPartVarReplaced;
}
}
}
return text;
}
private void OnConversationLine(Subtitle subtitle)
{
subtitle.formattedText.text = FilterText(subtitle.formattedText.text);
}
private void OnConversationResponseMenu(Response[] responses)
{
for (int i = 0; i < responses.Length; i++)
{
responses[i].formattedText.text = FilterText(responses[i].formattedText.text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment