- Home /
Question by
PijusVose · Jun 01, 2018 at 05:45 PM ·
c#eventssubscription
C# event does not work
For some reason, one of my event is not called. Here is the EventController method:
public void CallPlaceBuilding(WorldTile tile, BaseBuilding building, int lvl)
{
if (PlaceBuilding != null)
{
Debug.Log("[CallPlaceBuilding]: initialized.");
PlaceBuilding(tile, building, lvl);
}
}
Here is the part where the code is fired:
// Spawn buildings on tiles.
Building[] buildings = gameController.gameBuildings.ToArray();
for (int i = 0; i < buildings.Length; i++)
{
Debug.Log("[GenerateTileMap]: placing building.");
WorldTile newTile = GetTile(buildings[i].tilePosition);
eventController.CallPlaceBuilding(newTile, buildings[i].buildingType, buildings[i].buildingLevel);
}
And the method which is subscribed to PlaceBuilding:
private void SubscribeEvents()
{
eventController.PlaceBuilding += OnPlaceBuilding;
}
public void OnPlaceBuilding(WorldTile tile, BaseBuilding buildingType, int level)
{
GameObject buildingLevelGraphic = GetLevelGraphic(buildingType, level);
Debug.Log("[OnPlaceBuilding]: graphic found."); // this is not showed on console.
if (buildingLevelGraphic != null)
{
// code here.
}
}
Comment
Answer by Tobychappell · Jun 01, 2018 at 07:58 PM
If there are no errors in the console being thrown before the event is called then the code seems fine,
Put a Debug.Log after the method is subscribed to PlaceBuilding to check it's actually being subcribed. I often have a habit of implementing a system then find nothing is happening because I'm not calling that one method that kicks everything off lol.
Might also want to check order of statements being executed, like is the event being cleared (set to null) after the method is subscribed?