Last active
April 29, 2024 17:49
-
-
Save cbaltzer/6196131 to your computer and use it in GitHub Desktop.
Invoke with parameters!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
using System.Reflection; | |
using System.Collections; | |
namespace UnityEngine { | |
public static class ExtensionMethods { | |
public static void Invoke(this MonoBehaviour behaviour, string method, object options, float delay) { | |
behaviour.StartCoroutine(_invoke(behaviour, method, delay, options)); | |
} | |
private static IEnumerator _invoke(this MonoBehaviour behaviour, string method, float delay, object options) { | |
if (delay > 0f) { | |
yield return new WaitForSeconds(delay); | |
} | |
Type instance = behaviour.GetType(); | |
MethodInfo mthd = instance.GetMethod(method); | |
mthd.Invoke(behaviour, new object[]{options}); | |
yield return null; | |
} | |
} | |
} |
Thanks for your code! However, it does not work with methods that have the same name but a different set of parameters. I tried to improve your code, now it can find a specific implementation of the method. I also added the ability to set many parameters. I hope this helps someone)
`using UnityEngine;
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
namespace UnityEngine
{
public static class ExtensionMethods1
{
public static void Invoke(this MonoBehaviour behaviour, string method, object options, float delay)
{
behaviour.StartCoroutine(_invoke(behaviour,method, delay, options));
}
private static IEnumerator _invoke(this MonoBehaviour behaviour, string method, float delay, params object[] obj)
{
if (delay > 0f)
{
yield return new WaitForSeconds(delay);
}
Type instance = behaviour.GetType();
MethodInfo[] mth = instance.GetMethods();
List<MethodInfo> mthd = new List<MethodInfo>();
for (int i = 0; i < mth.Length; i++)
{
if (mth[i].Name == method)
{
mthd.Add(mth[i]);
}
}
if (mthd.Count == 1)
{
mthd[0].Invoke(behaviour, obj);
}
else
{
for (int i = 0; i < mthd.Count; i++)
{
ParameterInfo[] par = mthd[i].GetParameters();
if (par.Length == obj.Length)
{
bool IsCorrect = true;
for (int g = 0; g < par.Length; g++)
{
if (par[g].ParameterType != obj[g].GetType())
{
IsCorrect = false;
break;
}
}
if (IsCorrect)
{
mthd[i].Invoke(behaviour, obj);
}
}
}
}
yield return null;
}
}
}`
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used it for netcode dev, just copy this script in and then it is as easy as calling:
ExtensionMethods.Invoke(this, "OnClientDCClientRpc", default, 2f / NetworkManager.Singleton.NetworkTickSystem.TickRate);