Skip to content

Instantly share code, notes, and snippets.

@hecomi
Created August 22, 2016 15:53
Show Gist options
  • Save hecomi/c6e982478d748fa392b88f34ef2a5373 to your computer and use it in GitHub Desktop.
Save hecomi/c6e982478d748fa392b88f34ef2a5373 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
public class SyncPlayerUI : NetworkBehaviour
{
[SyncVar(hook="OnIdChanged")]
private string id_;
[SyncVar(hook="OnMessageChanged")]
private string message_;
public Text uiId;
public Text uiMessage;
public GameObject face;
public GameObject body;
public string iconServerUri = "ICON_SERVER_URL";
[ClientCallback]
void Awake()
{
uiId.GetComponent<InputPlayerText>().onTextChanged += OnInputIdChanged;
uiMessage.GetComponent<InputPlayerText>().onTextChanged += OnInputMessageChanged;
}
public override void OnStartClient()
{
if (!isLocalPlayer) {
uiId.GetComponent<InputPlayerText>().inputText = id_;
uiMessage.GetComponent<InputPlayerText>().inputText = message_;
}
StartCoroutine(FetchIcon(id_));
StartCoroutine(FetchColor(id_));
}
[ClientCallback]
void OnDestroy()
{
uiId.GetComponent<InputPlayerText>().onTextChanged -= OnInputIdChanged;
uiMessage.GetComponent<InputPlayerText>().onTextChanged -= OnInputMessageChanged;
}
[Client]
private void OnInputIdChanged(string id)
{
CmdSetId(id);
}
[Client]
private void OnInputMessageChanged(string message)
{
CmdSetMessage(message);
}
[Command(channel=2)]
public void CmdSetId(string id)
{
id_ = id;
}
[Command(channel=2)]
public void CmdSetMessage(string message)
{
message_ = message;
}
[Client]
void OnIdChanged(string id)
{
if (!isLocalPlayer) {
uiId.text = id;
}
StartCoroutine(FetchIcon(id));
StartCoroutine(FetchColor(id));
}
[Client]
void OnMessageChanged(string message)
{
if (!isLocalPlayer) {
uiMessage.text = message;
}
}
IEnumerator FetchColor(string id)
{
yield return new WaitForEndOfFrame();
if (id != "" && id != null) {
int maxTry = 5;
for (int cnt = 0; cnt < maxTry; ++cnt) {
var url = iconServerUri + "color/" + id;
var www = new WWW(url);
yield return www;
if (www.error != null) {
Debug.LogError(www.error);
yield return new WaitForSeconds(1f);
continue;
}
var c = www.text.Split(new string[] {","}, System.StringSplitOptions.None);
var color = new Color32(byte.Parse(c[0]), byte.Parse(c[1]), byte.Parse(c[2]), 255);
body.GetComponent<Renderer>().material.color = color;
}
}
}
IEnumerator FetchIcon(string id)
{
yield return new WaitForEndOfFrame();
if (id != "" && id != null) {
int maxTry = 5;
for (int cnt = 0; cnt < maxTry; ++cnt) {
var url = iconServerUri + id;
var www = new WWW(url);
yield return www;
if (www.error != null) {
Debug.LogError(www.url + ": " + www.error);
yield return new WaitForSeconds(1f);
continue;
}
face.GetComponent<Renderer>().material.mainTexture = www.texture;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment