簡體   English   中英

無法在Unity3D內部的C#編碼腳本中實例化byte []數組; 我該如何解決?

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

所以我試圖在我的統一項目和另一個充當服務器的窗口之間發送/接收消息。 我不能將stream.Read()與現在的字節數組一起使用。 它說這是一個NullReferenceException,雖然我認為是沒有實例化的。 這可能是一件非常簡單的事情,但確實讓我感到煩惱。 這是代碼; 給出異常的行是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);

    }
}

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

確實沒有多少代碼。 我只是為它說沒有實例化而感到沮喪。 它可能沒有有效的數據,但是我還是創建了它。 它可以在Visual Studio項目中使用,而當我在Unity3D中使用它時則不能。

  1. 您需要雙重確保在調用Start()之前未調用Update()-這在代碼中已經發生了數十次,人們首先連接事件處理程序,然后進行初始化。

  2. 在當前狀態下,如果Start()內有一個異常,則您根本不會通過它的外觀來處理它,因此“客戶端”可能返回空值,這實際上是導致異常的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM