Simplify a bit by parsing strings into arguments and executing methods

We often encounter this kind of situation, first parse the string into float or int, bool, etc., or parse the json string into an object and then use it as a parameter of the method, always write some repetitive code, in order to avoid For this problem, this class has been developed, and it is still working fine.

Well, these are the codes, put them here as a backup, huh, huh.

using System;
using UnityEngine;
using UnityEngine.Events;

public class ParseExecute
{
	static public void Float(string strValue, UnityAction<float> act)
	{
		float val;
		if (float.TryParse(strValue, out val))
		{
			act?.Invoke(val);
		}
		else
		{
			Debug.Log("U3DLog:ParseExecute.Float failed,because can NOT parse " + strValue + " to float.");
		}
	}

	static public void Int(string strValue, UnityAction<int> act)
	{
		int val;
		if (int.TryParse(strValue, out val))
		{
			act?.Invoke(val);
		}
		else
		{
			Debug.Log("U3DLog:ParseExecute.Int failed,because can NOT parse " + strValue + " to int.");
		}
	}

	static public void Bool(string strValue, UnityAction<bool> act)
	{
		bool val;
		if (bool.TryParse(strValue, out val))
		{
			act?.Invoke(val);
		}
		else
		{
			Debug.Log("U3DLog:ParseExecute.Bool failed,because can NOT parse " + strValue + " to bool.");
		}
	}

	static public void Json<T>(string json, UnityAction<T> act)
	{
		T t = JsonUtility.FromJson<T>(json);
		if (t != null)
		{
			act?.Invoke(t);
		}
		else
		{
			string tName = t.GetType().Name;
			Debug.Log("U3DLog:ParseExecute.Json<" + tName + "> failed,because can NOT parse " + json + " to " + tName + ".");
		}
	}
}

Guess you like

Origin blog.csdn.net/ttod/article/details/130781610