找回密码
 立即注册
楼主: fjkrl

[脚本] Unity3D中实现聊天功能的C#代码

[复制链接]
发表于 2013-3-5 22:06 | 显示全部楼层 |阅读模式

Unity3D中实现聊天功能的C#代码如下:

using UnityEngine;

using System.Collections;

public class Chat : MonoBehaviour {

bool usingChat = false;

bool showChat = false;

string inputField = "";

Vector2 scrollposition;

int width = 500;

int height = 200;

string playerName;

float lastUnfocusTime = 0;

Rect window;

ArrayList playerList = new ArrayList();

class PlayerNode

{

public string playerName;

public NetworkPlayer player;//NetworkPlayer是一个数据结构,保存着你可以从网络定位的另一位玩家的信息。比如,基于NetworkPlayer你可以向另外一个玩家发送消息。

}

ArrayList chatEntries=new ArrayList();

class ChatEntry

{

public string name="";

public string text="";

}

// Use this for initialization

void Start () {

window = new Rect(Screen.width / 2-width/2,Screen.height-height+5,width,height);

}

void OnConnectedToServer()

{

playerName = PlayerPrefs.GetString("playerName","");

if(playerName=="")

{

playerName = "RandomName"+Random.Range(1,999);

}

ShowChatWindow();

networkView.RPC("TellServerOurName",RPCMode.Server,playerName);//在所有连接端调用一个RPC函数。

addGameChatMessage(playerName+" hase just joined the chat!");

}

void OnServerInitialized()

{

playerName = PlayerPrefs.GetString("playerName","");

if(playerName=="")

{

playerName = "RandomName"+Random.Range(1,999);

}

ShowChatWindow();

PlayerNode newEntry =new  PlayerNode();

newEntry.playerName = playerName;

newEntry.player = Network.player;

playerList.Add(newEntry);

addGameChatMessage(playerName+" hase just joined the chat!");

}

PlayerNode GetPlayerNode(NetworkPlayer netPlay)

{

foreach(PlayerNode entry in playerList)

{

if(entry.player==netPlay)

{

return entry;

}

}

Debug.LogError("GetPlayNode:Requested a playernode of non-existing player!");

return null;

}

void OnPlayerDisconnected(NetworkPlayer netPlayer)//当一个玩家从服务器上断开时在服务器端调用。

{

addGameChatMessage("A Player has discinnected");

playerList.Remove(GetPlayerNode(netPlayer));

}

void OnDisconnectedFromServer()

{

CloseChatWindow();

}

[RPC]

void TellServerOurName(string name,NetworkMessageInfo info)//NetworkMessageInfo 网络数据信息,刚从网络接收的数据的相关信息会被保存到这个结构中。它揭示了从哪里来(数据源),什么时间发送和什么网络视图发送;其中包括:数据源、发送时间、网络视图。

{

PlayerNode newEntry = new PlayerNode();

newEntry.playerName = playerName;

newEntry.player = Network.player;

playerList.Add(newEntry);

addGameChatMessage(playerName+" has just joined the chat!");

}

void CloseChatWindow()

{

showChat = false;

inputField = "";

chatEntries = new ArrayList();

}

void ShowChatWindow()

{

showChat = true;

inputField = "";

chatEntries = new ArrayList();

}

void OnGUI () {

if (!showChat) return;

if(Event.current.type==EventType.keyDown && Event.current.character=='\n' & inputField.Length<=0)

{

if(lastUnfocusTime + .25f < Time.time)

{

usingChat = true;

GUI.FocusWindow(5);

GUI.FocusControl("Chat input field");

}

}

window = GUI.Window(5,window,GlobalChatWindow,"");

}

void GlobalChatWindow(int id)

{

GUILayout.BeginVertical();

GUILayout.Space(10);

GUILayout.EndVertical();

scrollposition = GUILayout.BeginScrollView(scrollposition);

foreach(ChatEntry entry in chatEntries)

{

GUILayout.BeginHorizontal();

if (entry.name == " - ")

{

GUILayout.Label(entry.name + entry.text);

}

else

{

GUILayout.Label(entry.name+": "+entry.text);

}

GUILayout.EndHorizontal();

GUILayout.Space(2);

}

GUILayout.EndScrollView();

if(Event.current.type==EventType.keyDown && Event.current.character=='\n' & inputField.Length>0)

{

HitEnter(inputField);

}

GUI.SetNextControlName("Chat input field");

inputField = GUILayout.TextField(inputField);

if(Input.GetKeyDown("mouse 0"))

{

if(usingChat)

{

usingChat = false;

GUI.UnfocusWindow();

lastUnfocusTime = Time.time;

}

}

}

void HitEnter(string msg)

{

msg = msg.Replace('\n',' ');

networkView.RPC("ApplyGlobalChatText",RPCMode.All,playerName,msg);

}

[RPC]

void ApplyGlobalChatText(string name,string msg)

{

ChatEntry entry=new ChatEntry();

entry.name=name;

entry.text=msg;

chatEntries.Add(entry);

if(chatEntries.Count>4)

{

chatEntries.RemoveAt(0);

}

scrollposition.y=1000000;

inputField="";

}

void addGameChatMessage(string str)

{

ApplyGlobalChatText(" - ",str);

if(Network.connections.Length>0)

{

networkView.RPC("ApplyGlobalChatText",RPCMode.Others," - ",str);

}

}

}



发表于 2013-4-6 20:49 | 显示全部楼层
{:5_408:}{:5_408:}{:5_408:}
发表于 2013-5-16 21:51 | 显示全部楼层

我很懒,只想回复看看,另感谢楼主分享{:soso__16915934313317769624_2:}
发表于 2013-6-28 10:42 | 显示全部楼层

不错 不错 不错{:soso__3922851084632044791_6:}
发表于 2013-8-9 15:34 | 显示全部楼层

不错 不错 不错{:soso__3922851084632044791_6:}
发表于 2013-10-19 11:25 | 显示全部楼层
还没试,先谢谢楼主
发表于 2013-12-10 10:32 | 显示全部楼层
收藏了,先谢谢楼主
发表于 2014-1-25 00:31 | 显示全部楼层
不错哦,学习了。就不知道在高频率刷新聊天的时候效率是否过关
发表于 2017-2-26 14:32 | 显示全部楼层
楼主是超人
发表于 2017-2-26 14:20 | 显示全部楼层
真心顶
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-12-24 02:37 , Processed in 0.182332 second(s), 22 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表