facebook twitter hatena line email

「Unity/photon/pun1/変数同期/シンプル」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
行8: 行8:
 
#部屋入室時に以下コードを実行
 
#部屋入室時に以下コードを実行
 
  void OnJoinedRoom() {
 
  void OnJoinedRoom() {
     GameObject member = PhotonNetwork.Instantiate ("Member", new Vector3 (0.0f, 0.0f, 0.0f),
+
     GameObject member = PhotonNetwork.Instantiate("Member", new Vector3 (0.0f, 0.0f, 0.0f),
 
         Quaternion.Euler(Vector3.zero),0);
 
         Quaternion.Euler(Vector3.zero),0);
 
  }
 
  }

2022年12月6日 (火) 05:09時点における版

変数同期のサンプル

  1. ヒエラルキーにGameObjectをMemberという名前で作成
  2. MemberにAddComponentをしてPhotonViewを追加
  3. MemberにAddComponentをしてPhotonTransformViewを追加
  4. Memberに以下MemberScript.csも割り当てる。
  5. MemberのInspectorのPhotonViewのObserverdOptionにMemberScriptとPhotonTransformViewを指定する
  6. ヒエラルキーのMemberをプロジェクトのResourcesにプレハブとして追記する(ドラッグ)
  7. 部屋入室時に以下コードを実行
void OnJoinedRoom() {
    GameObject member = PhotonNetwork.Instantiate("Member", new Vector3 (0.0f, 0.0f, 0.0f),
        Quaternion.Euler(Vector3.zero),0);
}

MemberScript.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MemberScript : Photon.MonoBehaviour {
	public string str = "guest";
	public float x = 0f;
	public float y = 0f;
	// Use this for initialization
	void Start () {
	}
	// Update is called once per frame
	void Update () {
	}
	void OnMouseDrag()
	{
		Debug.Log ("member ownerId=" + GetComponent<PhotonView>().ownerId);
		Debug.Log ("member 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 OnPhotonSerializeView( PhotonStream stream, PhotonMessageInfo info )
	{
		if (stream.isWriting) {
			Debug.Log ("member isWriting="+str);
			//データの送信
			stream.SendNext(str);
			stream.SendNext(this.transform.position.x);
			stream.SendNext(this.transform.position.y);
		} else {
			Debug.Log ("member  isread="+str);
			//データの受信
			this.str = (string)stream.ReceiveNext();
			this.x = (float)stream.ReceiveNext();
			this.y = (float)stream.ReceiveNext();
			this.transform.position = new Vector3 (x, y, transform.position.z);
		}
	}
}