Reputation:
I'm doing a chess-like game in unity (c#) and i'm getting stuck trying to do an upcasting to send information from a child to another of an abstract class.
Basically, I have an abstract class that has an event/delegate with a function so it can be accessed by a child class like this:
public delegate void KingUnderAttack(int CurrentX, int CurrentY, int CurrentAttackerX, int CurrentAttackery, System.Type attacker, bool isKingWhite);
public event KingUnderAttack kingUnderAttack;
protected void RaiseKingUnderAttack(int CurrentX, int CurrentY, int CurrentAttackerX, int CurrentAttackerY, System.Type attacker, bool isKingWhite)
{
if (kingUnderAttack != null)
{
kingUnderAttack(CurrentX, CurrentY, CurrentAttackerX, CurrentAttackerY, attacker, isKingWhite);
}
}
and in my child Class i access it like this:
RaiseKingUnderAttack(CurrentX, CurrentY, x, y, typeof(Knight), isWhite);
and on the recieving child class:
private void Start()
{
kingUnderAttack += Knight_kingUnderAttack;
}
private void Knight_kingUnderAttack(int CurrentX, int CurrentY, int CurrentAttackerX, int CurrentAttackerY, System.Type attacker, bool isKingWhite)
{
Debug.Log(CurrentX);
Debug.Log(CurrentY);
Debug.Log(CurrentAttackerX);
Debug.Log(CurrentAttackerY);
Debug.Log(attacker);
Debug.Log(isKingWhite);
}
by debugging I could see that the abstract class receives the child information but the information doesn't reach the second child class. I'm really stuck trying to think why.
Upvotes: 2
Views: 1275
Reputation: 3058
Inheritance can be thought of as a sort of code template that is "inserted" into the source of the child class, therefore the descendant classes are completely independent of each other. Assuming your child classes are the game pieces and you are wanting to alert all of the pieces to the event, it's not going to work if your child class is raising the event. That is, unless every child object subscribes to that event on every other child object (we'll ignore the n2 event subscriptions for now), in which case, you're going to need to keep track of every child somewhere central, and if you're going to do that...
A better approach is to add the event to a GameObject
representing your game board (i.e. the class that orchestrates the pieces, game rules, etc., let's call that BoardManager
). The BoardManager
is responsible for subscribing to events on each piece and publishing events of interest to each piece (now we've only got 2n event subscriptions). This approach isn't all that far from the Flux architecture pattern.
(I'm going to use chess names in this example - and boy do I wish SO had a sequence diagram feature)
Knight
notifies BoardManager
it wants to move to x, y
BoardManager
checks validity, tells Knight
to move to x, y
Knight
tells BoardManager
"I'm done moving"BoardManager
notices that King
is under attack and sends out a notification to every piece of that factKing
is under attack...Upvotes: 3