facebook twitter hatena line google mixi email

Unity/photon/位置同期/アバター風

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

アバター風にしてみる

  1. unity/photon/位置同期/シンプル [ショートカット] の手順の続き
  2. Cubeの下にCanvasを追加
  3. CubeのCanvasの下にTextを追加
  4. Cubeの下のCanvasのRenderModeをWorldSpaceへ(これでCubeにText座標がくっつくようになる)
  5. CubeにBoxColliderが追加されていることを確認
  6. ヒエラルキートップにCanvas/InputTextとCanvas/Buttonを追加
  7. CubeのObserverdOptionにCubeScriptとPhotonTransformViewを追加
  8. CubeをPrefubに追加
  9. 以下スクリプトでPrefubのCubeを呼び出す
  • PhotonManager.cs
GameObject cube = PhotonNetwork.Instantiate ("Cube", new Vector3 (0.0f, 0.0f, 0.0f),
			Quaternion.Euler(Vector3.zero),0);
cube.name = "Cube"+cube.GetComponent<PhotonView>().ownerId;
  • CubeScript.sc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class CubeScript : Photon.MonoBehaviour {
	public string str = "guest1";
	void Awake() {
		this.name = "Cube"+GetComponent<PhotonView> ().ownerId;
		if (GetComponent<PhotonView> ().isMine) {
			GetComponent<Renderer> ().material.color = Color.red;
		}
		GameObject obj = GameObject.Find ("/Canvas/Button");
		if (GetComponent<PhotonView> ().isMine) {
			obj.GetComponent<Button> ().onClick.AddListener (OnClick);
		}
		SetCubeText ();
	}
	void OnMouseDrag()
	{
		Debug.Log ("ownerId=" + GetComponent<PhotonView> ().ownerId);
		Debug.Log ("isMine=" + GetComponent<PhotonView> ().isMine);
		if (GetComponent<PhotonView>().isMine) {
			GetComponent<Renderer> ().material.color = Color.red;
			Vector3 objectPointInScreen = Camera.main.WorldToScreenPoint (this.transform.position);
			Vector3 mousePointInScreen = new Vector3 (Input.mousePosition.x,
				 Input.mousePosition.y,
				 objectPointInScreen.z);
			Vector3 mousePointInWorld = Camera.main.ScreenToWorldPoint (mousePointInScreen);
			mousePointInWorld.z = this.transform.position.z;
			this.transform.position = mousePointInWorld;
		}
	}
	void OnClick()
	{
		if (GetComponent<PhotonView> ().isMine) {
			GameObject objstr = GameObject.Find ("/Canvas/InputField/Text");
			str = objstr.transform.GetComponent<Text> ().text;
		}
		SetCubeText ();
	}
	void SetCubeText()
	{
		Debug.Log("name="+this.name);
		GameObject objstr = GameObject.Find(this.name + "/Canvas/Text");
		try {
			objstr.transform.GetComponent<Text> ().text = str;
		} catch (NullReferenceException ex) {
		}
	}
	void OnPhotonSerializeView( PhotonStream stream, PhotonMessageInfo info )
	{
		if (stream.isWriting) {
			Debug.Log ("cube isWriting="+str);
			//データの送信
			stream.SendNext(str);

		} else {
			Debug.Log ("cube isread="+str);
			//データの受信
			this.str = (string)stream.ReceiveNext();
			SetCubeText ();
		}
	}
}