需要一些專業知識。目前我正在從一個類產卵玩家在創建對象,然後通過線定義變量線,像這樣的方式:創建播放器對象不能從構造函數中工作
Player p = new Player();
p.Avatar = go;
p.PlayerName = playerName;
p.ConnectionId = cnnId;
p.Avatar.GetComponentInChildren<TextMesh>().text = pName;
players.Add(cnnId, p);
和玩家類是一個簡單的點點結構是這樣的:
public class Player
{
public string PlayerName;
public GameObject Avatar;
public int ConnectionId;
}
這樣的工作,但我想擴大的參數和使用構造函數來創建,我試圖通過創建我的對象這樣的,而不是做我的播放器對象:
Player p = new Player(playerName, go, cnnId); p.Avatar.GetComponentInChildren<TextMesh>().text = pName; players.Add(cnnId, p);
,然後我創造了我的構造是這樣的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public struct Player {
Client client;
public string PlayerName { get; set; }
public GameObject Avatar { get; set; }
public int ConnectionId { get; set; }
public byte[] Tex { get; set; }
public string Type { get; set; }
public string Id { get; set; }
public int Strength { get; set; }
public int Hitpoints { get; set; }
public bool IsAlive { get; set; }
// Initial method takes base arguments for testing
public Player(string playerName, GameObject avatar, int connectionID) : this()
{
this.PlayerName = playerName;
this.Avatar = avatar;
this.ConnectionId = connectionID;
client.infoDisplayText.GetComponent<Text>().text += playerName + " " + ConnectionId + " " + "\n";
}
// Overload method takes all player arguments
public Player(string playerName, GameObject avatar, int connectionID, byte[] tex, string type, string id, int strength, int hitpoints, bool isAlive) : this()
{
this.PlayerName = playerName;
this.Avatar = avatar;
this.ConnectionId = connectionID;
this.Tex = tex;
this.Type = type;
this.Id = id;
this.Strength = strength;
this.Hitpoints = hitpoints;
this.IsAlive = isAlive;
Debug.Log(id + " : " + type + " created with strength " + strength + ", hit points " + hitpoints + ", and a texture the size of " + tex.Length);
client.infoDisplayText.GetComponent<Text>().text += playerName + " " + id + " : " + type + " created with strength " + strength + ", hit points " + hitpoints + ", and a texture the size of " + tex.Length +" \n";
}
}
當我嘗試使用類的構造方法,雖然它不工作 - 我的球員的名字沒有出現,我的球員的跑動沒有更新整個網絡了。我需要做些什麼改變來讓我的構造函數工作?
我使用進程派生我的球員功能齊全:
private void SpawnPlayer(string pName, int cnnId)
{
GameObject go = Instantiate(playerPrefab) as GameObject;
// Is this our player?
if (cnnId == ourClientId)
{
// Add mobility
go.AddComponent<Movement>(); // Add Movement.cs Script
// Remove Connect Button
if(GameObject.Find("Canvas").activeInHierarchy == true)
GameObject.Find("ConnectButton").SetActive(false);
isStarted = true;
}
Player p = new Player(playerName, go, cnnId);
p.Avatar.GetComponentInChildren<TextMesh>().text = pName;
players.Add(cnnId, p);
}
你爲什麼要用struct?如果你切換到一個班級,它是否能解決你的問題? –
您確定沒有收到任何NullReferenceException,尤其是在設置頭像遊戲對象時? –
@ScottChamberlain切換到類似乎不能解決問題。 – greyBow