0

I'm trying to instantiate an object in Unity whenever a function is called.

This is the start Method in my UiHandler script

public void Start() {

    GameObject obj = Instantiate(userPanelPrefab, userPanelContainer) as GameObject;

}

And this is my "OnPlayer" method, also in the UiHandler script, that is called every time a "player" enters the game. (They are not really players it is just names sent through a WebSocket server to Unity)

public void OnPlayer(WebsocketManager.PlayerEvent e) {
    Debug.Log("On Player");
    if (e.type == WebsocketManager.JOIN_TYPE) {
        Debug.Log("On Join");
        GameObject obj = Instantiate(userPanelPrefab, userPanelContainer) as GameObject;
        Debug.Log("Assign User Panel");
        UserPanel p = obj.GetComponent<UserPanel>();
        p.Set(e.name);
    }
}

When the start method is called, the Object instantiates as it should. But whenever the "OnPlayer" method is called, nothing happens and the code beneath the instantiate function doesn't even run. No errors or information is displayed in the console. It just does nothing.

The console output with the Debug messages is

  • On Player

  • On Join

the "Assign User Panel" log is also never displayed in the console.

For the WebSocket integration, I'm using Socket Sharp and the back-end socket server is running on NodeJs.

This is my WebSocket code in my WebsocketManager script

public const string JOIN_TYPE = "join";
WebSocket ws = new WebSocket("ws://10.0.0.8:3069/");

ws.OnMessage += (sender, m) => {
 string json = GetStringFromArray(m.Data);
    if (IsJson(json, out PlayerEvent ev)) {
        Debug.Log("Is Valid JSON");
        if (ev.type == JOIN_TYPE) {
            AddPlayer(ev.name);
        } else if (ev.type == LEAVE_TYPE) {
            RemovePlayer(ev.name);
        }
        uiHandler.OnPlayer(ev);
    }
}

Any help is appreciated!

ostpol
  • 1
  • 1
  • 3

1 Answers1

0

After you instantiate, you have to set the instantiated object to be a parent of the canvas, with InstantiatedObject.SetParent(canvasTransform);

SullyBully
  • 31
  • 1
  • 6
  • Unfortunately, that doesn't seem to work for me. As soon as the instantiate method is called, no other code inside the function is run and the instantiate method doesn't create the object at all – ostpol Dec 29 '19 at 21:48