Unity,WebSocketSharp Singleton:NullReferenceException:对象引用未设置为对象的实例

时间:2013-11-27 16:30:06

标签: websocket unity3d nullreferenceexception

我创建了具有webscoket连接的Singleton:

using UnityEngine;
using WebSocketSharp;

public class Singleton : MonoBehaviour
{
    private static Singleton instance;
    public WebSocket conn ; 

    public static Singleton Instance
    {

        get { 
            return instance ?? (instance = new GameObject("Singleton").AddComponent<Singleton>()); 
        }
    }

    public void Start() {
        WebSocket conn = new WebSocket ("ws://localhost:8080/");
        conn.Connect ();
        conn.Send ("connected");
    }

    public void DoSomeAwesomeStuff()
    {
        conn.Send ("msg 1");
        conn.Send ("msg 2");
        conn.Send ("msg 3");
    }
}

但是当我在那个地方使用它的时候:

Singleton.Instance.DoSomeAwesomeStuff ();

我收到消息“已连接”,但在午餐时DoSomeAwsomeStuff收到错误:

NullReferenceException: Object reference not set to an instance of an object

我做错了什么?

1 个答案:

答案 0 :(得分:1)

好的,我找到了解决方案:

public void Awake() { //Changed start to Awake
    conn = new WebSocket ("ws://localhost:8080/"); // removed WebSocket on begin
    conn.Connect ();
    conn.Send ("connected");
}

现在按预期工作