How could I use OnPhotonSerializeView?

bob picture bob · Jun 16, 2015 · Viewed 12.1k times · Source

I am currently to to instantiate a box when the player drops it (using "PhotonNetwork.Instantiate"). Now this box, when the player drops it is given data about that box, in the form of an Enum and then distributes the value to the box. But, when the other client picks it up, the box has no values.

When user client drops box:

When other client drops it:

code:

    [RPC] void dropItem(Item item){

    Vector3 playerPos = this.transform.position;
    Vector3 playerDirection = this.transform.forward;
    Quaternion playerRotation = this.transform.rotation;
    float spawnDistance = 1;

    Vector3 spawnPos = playerPos + playerDirection*spawnDistance;
    string itemname = item.itemName;


    GameObject itemAsGameObject = (GameObject)PhotonNetwork.Instantiate("DroppedItem", spawnPos, playerRotation, 0);

    itemAsGameObject.GetComponent<DroppedItem> ().item = item;



}

As you can see the client that drops the box has the values. but they arent being passed over to the other clients on the network. how can i fix this?

Answer

Jacob Jarick picture Jacob Jarick · Mar 12, 2017

Here is a working example for you.

I wish to access x,y,z from cube.cs for the clients. cube.cs is attached to a prefab that is spawned many times by the server when the room is joined by master.

on the prefab I create a PhotoView and then drag the cube.cs script (which is also attached to the same prefab) to PhotonView's "Observed Components".

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

[RequireComponent(typeof(PhotonView))]
public class cube : Photon.MonoBehaviour
{
    [SerializeField]
    public int x;
    [SerializeField]
    public int y;
    [SerializeField]
    public int z;
    [SerializeField]
    public int value;

    void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.isWriting)
        {
            stream.SendNext(x);
            stream.SendNext(y);
            stream.SendNext(z);
        }
        else
        {
            x = (int)stream.ReceiveNext();
            y = (int)stream.ReceiveNext();
            z = (int)stream.ReceiveNext();
        }
    }
}