Playmaker Forum

PlayMaker Updates & Downloads => Share New Actions => Topic started by: Zenfish on November 17, 2021, 03:53:06 PM

Title: String Multi Replacement
Post by: Zenfish on November 17, 2021, 03:53:06 PM
Hi,
Here is my first and very small contribution to Playmaker.
Well it's not crazy I grant you but it can save you from multiplying the base action.
As its name suggests, it allows you to modify several substrings from a base string.

EDIT: You can now choose whether to overwrite the previous replacements. for example:
With overwrite: Change A to B and B to C will give CC as result
Without overwrite: Change A to B and B to C will give BC as result


Code: [Select]
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.String)]
[Tooltip("Replace multiple substrings with new Strings")]
public class StringMultipleReplacement : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The String Variable to examine.")]
public FsmString stringVariable;
[CompoundArray("String replacements", "replace", "with")]
[Tooltip("Replace this string...")]
public FsmString[] replace;
[Tooltip("... with this string.")]
public FsmString[] with;
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("Overwrite previous replacements")]
public bool overwritePrevious;
[Tooltip("Store the result in a string variable.")]
public FsmString storeResult;
[Tooltip("Repeat every frame.")]
public bool everyFrame;

public override void Reset()
{
stringVariable = null;
replace = new FsmString[1];
with = new FsmString[1];
overwritePrevious = false;
storeResult = null;
everyFrame = false;
}

public override void OnEnter()
{
DoReplace();
if (!everyFrame)
Finish();
}

public override void OnUpdate()
{
DoReplace();
}

void DoReplace()
{
if (stringVariable == null) return;
if (storeResult == null) return;
storeResult.Value = stringVariable.Value;
if (overwritePrevious)
{
for (int i = 0; i < replace.Length; i++)
{
storeResult.Value = storeResult.Value.Replace(replace[i].Value, with[i].Value);
}
}
else
{
for (int i = 0; i < replace.Length; i++)
{
storeResult.Value = storeResult.Value.Replace(replace[i].Value, ("Rep#" + i + "#"));
}
for (int i = 0; i < replace.Length; i++)
{
storeResult.Value = storeResult.Value.Replace(("Rep#" + i + "#"), with[i].Value);
}
}
}
}
}
Title: Re: String Multi Replacement
Post by: Fat Pug Studio on November 18, 2021, 05:16:23 AM
Great one!
Title: Re: String Multi Replacement
Post by: Zenfish on November 19, 2021, 06:23:52 PM
Thank Fat Pug!