'Comparing Action.Method of a stored method and a method of a passed method parameter results in false though they are the same
Im trying to learn something about delegates, actions etc. Im trying to make a script, that makes the methods from other scripts only activate once, if you pass the method as a parameter, and cant be activated again, if you pass the same method as a parameter again. To store the methods from other scripts, im using a List of Actions (Im making it like that, so I can compare a stored method with a passed method and see, if it was already activated). The comparing between a passed method and a stored method only results in false in resetMethod() , because the Action.Method of both is different even though they are the same. Debug.Log() says
Void <Jump>b__15_0()
Void <Move>b__14_1()
How do I fix it?
public class CallMethodOnce : MonoBehaviour
{
public class Method
{
public Action method {get;}
public bool called {get; set;}
public Method(Action method, bool called = false)
{
this.method = method;
}
}
List<Method> methods = new List<Method>();
public void callMethodOnce(Action method)
{
Method _method = new Method(method);
Method methodToCall = null;
if (methods.Count != 0)
{
for (int i = 0; i < methods.Count; i++)
{
if (object.ReferenceEquals(_method.method, methods[i].method))
{
methodToCall = methods[i];
methods.Remove(_method);
}
else
{
methods.Add(_method);
methodToCall = _method;
}
}
}
else
{
methods.Add(_method);
methodToCall = _method;
}
Debug.Log(methodCalled(methodToCall));
if (methodCalled(methodToCall)) return;
methodToCall.method();
methodToCall.called = true;
}
public void resetMethod(Action method)
{
foreach(Method m in methods)
{
Debug.Log(method.Method + "\n" + m.method.Method);
if (object.ReferenceEquals(method, m.method))
{
Debug.Log("reseted");
m.called = false;
}
}
}
bool methodCalled(Method method)
{
return method.called;
}
}
Here are the only parts the script is used in. This
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
timerCreater.SetTimer(0.25f, () => Jump());
onceMethodCaller.callMethodOnce(() =>
AnimationParameterController.ChangeParameter(AnimationParameterController.jumped, true));
return;
}
and this
void Jump()
{
if (!isGrounded) return;
ySpeed = jumpHeight;
playerRb.velocity += new Vector3(0, ySpeed, 0);
onceMethodCaller.resetMethod(() => AnimationParameterController.ChangeParameter(AnimationParameterController.jumped, true));
}
Solution 1:[1]
Delegate.ReferenceEquals() did the job for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dracolyte |
