简体   繁体   中英

Adding Event listener Function through C# but still missing it

I am getting strange behvaiour I don't know Why? I am adding function at Add listener on button click event but still its is missing as I reload my scene. I have this function. (Its getting desired button object correctly i have tested)

 public void SetupMenuSceneButtons()
    {
        if (GameObject.Find("BtnStartHost"))
            Debug.Log("BtnStartHost found");
        if (GameObject.Find("BtnJoinGame"))
            Debug.Log("BtnJoinGame found");

        GameObject.Find("BtnStartHost").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find("BtnStartHost").GetComponent<Button>().onClick.AddListener(delegate { StartupHost(); });
        GameObject.Find("BtnJoinGame").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find("BtnJoinGame").GetComponent<Button>().onClick.AddListener(delegate { JoinGame(); });

    }

I am calling above function on OnLevelWasLoaded event but its function assignment on click is still missing and my buttons are not working as i reload my scene. I have also tried Add event listener without delegate but same problem.

 GameObject.Find("BtnJoinGame").GetComponent<Button>().onClick.AddListener(JoinGame);

I have also tried assignment through this but still problem persist.

GameObject.Find("BtnStartHost").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find("BtnStartHost").GetComponent<Button>().onClick.AddListener(()=> { StartupHost(); });
        GameObject.Find("BtnJoinGame").GetComponent<Button>().onClick.RemoveAllListeners();
        GameObject.Find("BtnJoinGame").GetComponent<Button>().onClick.AddListener(() => { JoinGame(); });

I ran a test of your code on v5.5, OnLevelWasLoaded is just not called and triggers a warning for being deprecated (funny it still autocomplete in VS).

The following is working:

 void OnEnable()
 {
     SceneManager.sceneLoaded += SceneManager_sceneLoaded; ;
 }

private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
{
    SetupMenuSceneButtons();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM