简体   繁体   中英

Cannot Instantiate byte[] array in C# coding scripts inside Unity3D; How do I fix that?

So I am trying to send/receive messages between my unity project and another window that acts as the server. I cannot use stream.Read() with the byte array I have now. It says it is a NullReferenceException and is not instantiated though I think it is. It may be something super simple, but it is really bugging me lol. Here's the code; the line that gives the exception is the stream.Read(....):

using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.IO;

public class Client_Script : MonoBehaviour {

byte[] SendBuffer = null;
TcpClient client = null;
NetworkStream stream = null;
int PortNumber = 3003;
string IP = "192.168.1.100";

// Use this for initialization
void Start () {

    try
    {

        SendBuffer = new byte[1024];
        client = new TcpClient();
        client.Connect(IP, PortNumber);

    }
    catch (Exception e)
    {   

        //"Couldn't connect to destination"

    }

    stream = client.GetStream();

}

// Update is called once per frame
void Update () {

    stream.Read (SendBuffer, 0, 1024);

    string message = BitConverter.ToString (SendBuffer);

    ASCIIEncoding encoder = new ASCIIEncoding ();

    SendBuffer = encoder.GetBytes (message);

    stream.Write (SendBuffer, 0, SendBuffer.Length);

    }
}

===============================================================

It really isn't much code; I am just frustrated at how it says it is not instantiated even though it is. It may have no valid data in it, but I created it anyways. It works in Visual Studio projects, just not when I use it inside of Unity3D.

  1. You need to make doubly sure that Update() isn't being called before a call to Start() - seen this dozens of times in code where people hook up event handlers first, then they initialize.

  2. In the present state, if there's an exception inside of Start(), you're not handling it at all by the looks of it, so 'client' may be returning a null value and this is what actually be the cause of the exception.

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