Search Unity

Event won't be handled

Discussion in 'Scripting' started by lrapp, Aug 25, 2018.

  1. lrapp

    lrapp

    Joined:
    Feb 25, 2017
    Posts:
    3
    Hey guys, I'm trying to assign the player in my Camera script through an event called when the player joins, but for some reason, it won't handle the Event Handler I have in my camera script. OnLocalPlayerJoined is called when the player sets itself in the gamemanager.

    In the Camera Script (the print is never executed)
    Code (CSharp):
    1.  
    2. void Start ()
    3.     {
    4.         GameManager.Instance.OnLocalPlayerJoined += HandleOnLocalPlayerJoined;
    5.     }
    6.  
    7. private void HandleOnLocalPlayerJoined(Player player)
    8.     {
    9.         print("Handling Player");
    10.         localPlayer = player;
    11.     }
    This is the set code in my Game Manger that the player calls when it awakes (print is executed).
    Code (CSharp):
    1. set
    2.         {
    3.             m_LocalPlayer = value;
    4.             Debug.Log("Player set");
    5.             if(OnLocalPlayerJoined != null)
    6.             {
    7.                 OnLocalPlayerJoined(m_LocalPlayer);
    8.             }
    9.         }
    I create my event like this:
    Code (CSharp):
    1. public class GameManager {
    2.  
    3.     public event System.Action<Player> OnLocalPlayerJoined;
    4. // [...]
    5. }
    I've already modified the execution order so that the camera script gets executed after the player script where he sets himself and calls the event and also vice versa.

    Sorry if I butchered any code jargon, I'm quite a beginner. Thanks for your time :)
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,975
    You say "when it awakes" which makes me think that you have a simple execution order issue in the sense that Awake runs before any Start method. Try changing the event registration from Start to Awake.
     
  3. lrapp

    lrapp

    Joined:
    Feb 25, 2017
    Posts:
    3
    Ah, I forgot to say that it worked great in the previous Version, 2018.2.3
    Now on 2018.2.5 it broke. Sorry
    Gonna try your solution anyway though, thanks :)
     
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    5,975
    Could be a Script Execution Order issue. Sometimes order changes when changing Unity versions, as there is no guaranteed way that one script's Awake/Start runs before another's at all times.

    Perhaps add a Debug.Log before event registration and when the event is sent out (before the null check) to see if that is the case.
     
  5. lrapp

    lrapp

    Joined:
    Feb 25, 2017
    Posts:
    3
    Thanks for your insights :)
    Sadly, Unity decided to throw my hours trying to fix the problem out of the window, and the script now works again after the 3rd reboot ._. Thanks anyways