0

I'am working on a Unity project where I want to make use of socketIO. I want a method that simply emits a socket to my server. Example: A button that when I click that it emits something.

My code is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SocketIO;

public class SocketIOScript : MonoBehaviour {

    private void Awake() {
        print ("awake");
    }

    public SocketIOComponent socket;

    void Start() {
        StartCoroutine (ConnectToServer ());
        socket.On ("USER_CONNECT", OnUserConnect);
    }

    //this works
    IEnumerator ConnectToServer() {
        yield return new WaitForSeconds (0.5f);
        socket.Emit ("USER_CONNECT");
    }

    //When I call on this from a button etc, the socket gives an NullException
    public void logIn() {
        socket.Emit("something");
    }

    public void OnUserConnect(SocketIOEvent socketIOEvent) {
        print ("USER_CONNECT returned");
    }
}

The USER_CONNECT socket works and I confirmed that on my server and responded. But when I call the LogIn method I get this exception: NullReferenceException: Object reference not set to an instance of an object SocketIOScript.logIn () (at Assets/SocketIOScript.cs:27)

Can someone explain why my socket value is suddenly Null and how to fix it? Thanks!

RvEng
  • 23
  • 2
  • 1
    It means that `socket` is not initialized. Since `SocketIOComponent` is component, maybe do something like this: `socket = gameObject.AddComponent()`.... – Programmer Jul 27 '17 at 11:01
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mrogal.ski Jul 27 '17 at 11:41

0 Answers0