- Home /
Having trouble subscribing to events from external class
So I have a class whose main job is to manage game logic like game mode, menu behavior, and to capture player input and relay it to other classes:
public class GameLogic : MonoBehaviour {
public delegate void OnAttack();
public static event OnAttack SuccesfulAttack;
void Update(){
if (Input.GetButtonDown("Attack"))
SuccesfulAttack();
}
}
public class Combat : MonoBehaviour {
void DoDamage(){
}
}
I would like to subscribe DoDamage in the Combat class to my SuccessfulAttack event, so every time the logic component determines that an attack has been landed successfully, all related functions take effect.
I've been trying to do it through GameLogic's Awake:
void Awake(){
Combat myCombat = gameObject.GetComponent<Combat>();
SuccesfulAttack += myCombat;
}
However, I get an error, "Value does not fall within the expected range"- is this the wrong way to do this?
Answer by abhi_360 · May 20, 2015 at 10:31 AM
change these things
Make DoDamage() public
Change this line SuccesfulAttack += myCombat; to SuccesfulAttack += myCombat.DoDamage;
Hmm, I see where the problem was, but I still have an error;
SuccesfulAttack += myCombat.DoDamage;
results in "Operator '+=' cannot be applied to operands of type GameLogic.OnAttack' and 'void'"
That is probably because you did OnAttack += ins$$anonymous$$d of SuccesfulAttack +=
$$anonymous$$ake sure your DoDamage() functions return type void and has no arguments and OnAttack also has the same signatures
I'm pretty sure they do, this is weird... here's the complete code, this is in GameLogic:
void Awake(){
Combat myCombat = gameObject.GetComponent<Combat>();
SuccesfulAttack += myCombat.DoDamage();
}
and this is in Combat:
public void DoDamage(){
Debug.Log ("Did damage!");
}
dude SuccesfulAttack += myCombat.DoDamage; no paranthesis
Answer by HTwist · May 20, 2015 at 10:23 AM
You are subscribing an object "myCombat" to the event which is not correct. You should be subscribing a method which has the same signature as your delegate.
Your answer