A case of Photon synchronized scene

Goal

  • When player touch the sample cube and press B, center cube turn blue.
  • When player touch the sample cube and press R, center cube turn red.
  • Use photon to synchronize在這裏插入圖片描述

Step 1: Make Player Move

  • Add MoveCube to Player
using UnityEngine;
using System.Collections;
using Photon.Pun;

// This script moves the character controller forward
// and sideways based on the arrow keys.
// It also jumps when pressing space.
// Make sure to attach a character controller to the same game object.
// It is recommended that you make only one call to Move or SimpleMove per frame.

public class MoveCube : MonoBehaviourPun
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;

    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded&&
            PhotonNetwork.IsConnected&&//check whether connect
            photonView.IsMine)//check whether is mine
        {
            // We are grounded, so recalculate
            // move direction directly from axes

            moveDirection = new Vector3(-Input.GetAxis("Vertical"), 0.0f, Input.GetAxis("Horizontal"));
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);
    }
}

2. Store the material to the cube

2.1. Create Material

在這裏插入圖片描述

2.2. Attach Center Cube to CenterCube

在這裏插入圖片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CenterCube : MonoBehaviour
{
    public Material[] material;

    public int curMaterial;

    private void Awake()
    {
        curMaterial = 2;
    }
    private void OnTriggerStay(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            Debug.Log("In");
            if(Input.GetKeyDown(KeyCode.B))
            {
                GetComponent<MeshRenderer>().material = material[0];
                curMaterial = 0;
            }else if(Input.GetKeyDown(KeyCode.R))
            {
                GetComponent<MeshRenderer>().material = material[1];
                curMaterial = 1;
            }
        }
    }
}

3. Set the photon network

3.1. Create an empty gameobject and name it as NetworkLauncher

在這裏插入圖片描述

3.2. Attach the NetworkLauncher script to the NetworkLauncehr

在這裏插入圖片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class NetworkLauncher : MonoBehaviourPunCallbacks
{

    // Start is called before the first frame update
    void Start()
    {
        PhotonNetwork.ConnectUsingSettings();
    }

    public override void OnConnectedToMaster()
    {
        base.OnConnectedToMaster();
        Debug.Log("Welcome");

        PhotonNetwork.JoinOrCreateRoom("Room",
            new Photon.Realtime.RoomOptions() { MaxPlayers = 2 }, default);
    }
    public override void OnJoinedRoom()
    {
        base.OnJoinedRoom();

        GameObject obj = PhotonNetwork.Instantiate("Player", new Vector3(2.84f, 1f, -4.79f),
            Quaternion.identity, 0);
        obj.tag = "Player";

    }
}

3.2. Drag the Player to the resource directory in photon

在這裏插入圖片描述

3.3. Add photon component to the Player

在這裏插入圖片描述

  • Remember drag the “Photon Transform View” to the Observed Components.
  • Remember to override the prefab.

3.4. Delete the Player in hierarchy

在這裏插入圖片描述

4. Run the project to check whether generate the player

在這裏插入圖片描述

4.1. Build another window to check sychronize

在這裏插入圖片描述

  • We find that the player position is synchronized but the center cube color is not sychronze.

5. Add this two component to the center cube

在這裏插入圖片描述

5.1. Write code in PhotonColorNumView

using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = System.Object;

[RequireComponent(typeof(PhotonView))]
[RequireComponent(typeof(CenterCube))]
[AddComponentMenu("Photon Networking/Photon ColorNum View")]
public class photonColorNumView : MonoBehaviour, IPunObservable
{
    [SerializeField]
    bool m_SynchronizeColorNum = true;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            if (m_SynchronizeColorNum)
            {
                int colorNum = GetComponent<CenterCube>().curMaterial;
                stream.SendNext(colorNum);

            }
        }
        else
        {
            if (m_SynchronizeColorNum)
            {
                GetComponent<MeshRenderer>().material = GetComponent<CenterCube>().material[
                    (int)stream.ReceiveNext()];
            }
        }
    }
}
  • Drag the script to the photon view
    在這裏插入圖片描述

6. Build the project

在這裏插入圖片描述

  • Only the window build first can control the color

6.1. Add this line to Center Cube, make sure the player touch the object is the master client

using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CenterCube : MonoBehaviourPun
{
    public Material[] material;


    public int curMaterial;

    private void Awake()
    {
        curMaterial = 2;
    }
    private void OnTriggerStay(Collider other)
    {
        //Add this line
        PhotonNetwork.SetMasterClient(PhotonNetwork.LocalPlayer);
        if(other.CompareTag("Player"))
        {
            Debug.Log("In");
            if(Input.GetKeyDown(KeyCode.B))
            {
                GetComponent<MeshRenderer>().material = material[0];
                curMaterial = 0;
            }else if(Input.GetKeyDown(KeyCode.R))
            {
                GetComponent<MeshRenderer>().material = material[1];
                curMaterial = 1;
            }
        }
    }
}

SUCCESS!!

Link

項目地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章