Unity/photon/pun1/位置同期/アバター風
提供: 初心者エンジニアの簡易メモ
アバター風にしてみる
- unity/photon/pun1/位置同期/シンプル [ショートカット] の手順の続き
- Cubeの下にCanvasを追加
- CubeのCanvasの下にTextを追加
- Cubeの下のCanvasのRenderModeをWorldSpaceへ(これでCubeにText座標がくっつくようになる)
- CubeにBoxColliderが追加されていることを確認
- ヒエラルキートップにCanvas/InputTextとCanvas/Buttonを追加
- CubeのObserverdOptionにCubeScriptとPhotonTransformViewを追加
- CubeをPrefabに追加
- 以下スクリプトでPrefabのCubeを呼び出す
- PhotonManager.cs
GameObject cube = PhotonNetwork.Instantiate("Cube", Vector3.zero, 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 (); } } }