1

I am making a simple networking game. The scene has a button named 'ReloadButton' and i am trying to find this button and add a listener to it through my script attached on the player.

    private Button reloadBtn;

    void Start()
    {
        GameObject tempGO = GameObject.Find("ReloadButton");

        if (tempGO != null)
        {
            reloadBtn = tempGO.GetComponent<Button>();
            reloadBtn.onClick.AddListener(weaponManager.Reload);
        }
    }

I am doing it this way because direct referencing of 'ReloadButton' to the script through public Buttonvariable is not possible.

The code works fine on the server, the listener is also added correctly. but on the client, the GameObject.Find("ReloadButton") throws a NullReferenceException.

Seems like the client cannot find the Button itself. I cannot proceed further in my project without solving this problem, I hope some of you can point me towards the problem.

  • Is the button in the scene before you start the game, or are you instantiating it? – Hristo Apr 08 '17 at 07:25
  • @Hristo It is already in the scene. – Abhishek Hingorani Apr 08 '17 at 07:26
  • And when you launch the client, is the button present in the hierarchy and is it active and enabled? – Hristo Apr 08 '17 at 07:27
  • GameObject.Find wont throw a NullReferenceException if it can't find it. Does the script inherit from MonoBehaviour? Does it exist on an object in the scene? – Fredrik Schön Apr 08 '17 at 07:28
  • Heres the documentation: https://docs.unity3d.com/ScriptReference/GameObject.Find.html – Fredrik Schön Apr 08 '17 at 07:28
  • @Fredrik its not the `GameObject.Find` that is throwing the exception. its the fact that he wants to access it afterwords (`tempGO.GetComponent – Hristo Apr 08 '17 at 07:29
  • @Fredrik.. Thank you for your replies, I am doing some other functionality in the update function. Maybe that is the problem. Here is the update function. `if (currentWeapon.bullets < currentWeapon.maxBullets) reloadBtn.gameObject.SetActive(true); else reloadBtn.gameObject.SetActive(false);` @Hristo – Abhishek Hingorani Apr 08 '17 at 07:32
  • It sounds weird that `tempGO.GetComponent – Fredrik Schön Apr 08 '17 at 07:50
  • 1
    If that was the case then it shouldn't have worked on the Server as well, but it works fine on the server. @Fredrik – Abhishek Hingorani Apr 08 '17 at 08:07
  • share the error with line number of error – Muhammad Faizan Khan Apr 08 '17 at 09:59
  • 2
    @Fredrik @Hristo @Mohammad Faizan Khan I solved it, In the update method, `reloadBtn.gameObject.setActive(false)` this line was disabling the component from server for all the clients, So before `if` condition i just added `if(isLocalPlayer)`. Now the button gets disabled only on local clients and everything works just fine. Thank you for the help :) – Abhishek Hingorani Apr 08 '17 at 10:56

0 Answers0