Basically I have achieved storing the methods but when I call them its like they are calling in a new Instance of an object instead of the object itself.
When I call the method it just prints 0
This is where I use it. It doesn't matter how many times I execute SumanNumero. When I call RPC_MetodoEjemplo I just get 0 (The variable is initialized with 5)
public class Something: NetworkBehaviour
int x = 5;
// Esto es un ejemplo de un rpc sin parámetros
[ClientRPC]
public void RPC_MetodoEjemplo()
{
Debug.Log(x);
}
public void SumanNumero()
{
x += 10;
}
}
This is my approach:
private List<RPCMethodInfo> clientRPCMethods = new List<RPCMethodInfo>();
public RPCManager()
{
// We obtain all the classes that inherits from NetworkBehaviour
Type[] networkBehaviours = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => typeof(NetworkBehaviour).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.ToArray();
// We obtain all the methods that have the ClientRPC attribute
foreach (Type networkBehaviour in networkBehaviours)
{
MethodInfo[] methods = networkBehaviour.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => x.GetCustomAttributes(typeof(ClientRPCAttribute), false).Length > 0)
.ToArray();
foreach (MethodInfo method in methods)
{
clientRPCMethods.Add(new RPCMethodInfo(method, networkBehaviour));
}
}
}
// Llama a este método desde el cliente para ejecutar un RPC
public void CallRPC(string methodName, object[] parameters)
{
foreach (var method in clientRPCMethods)
{
if (method.Method.Name == methodName)
{
method.Method.Invoke(method.Target, parameters);
return;
}
}
}
public class RPCMethodInfo
{
public MethodInfo Method { get; }
public object Target { get; }
public RPCMethodInfo(MethodInfo method, object target)
{
Method = method;
Target = target;
}
}
Thanks to @derHugo I did something.
Its not so effective but It is only called 1 time at the begining of the game so it is not that bad.(Could be better, probably when I finish the proyect i will refactor it)
This is it: