A case of Photon synchronized scene(Photon引擎同步案例[全英])

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

项目地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值