2

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?

4

2 回答 2

2

这是一个适合您的工作示例

我希望为客户从 cube.cs 访问 x,y,z。cube.cs 附加到一个预制件上,当房间被主人加入时,该预制件由服务器多次生成。

在预制件上,我创建了一个PhotoView,然后将 cube.cs 脚本(也附加到同一个预制件)拖到 PhotonView 的“观察到的组件”。

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();
        }
    }
}
于 2017-03-12T00:04:54.193 回答
0

如果您需要关卡中的对象,请尝试将其实例化为场景对象而不是常规实例化:PhotonNetwork.InstantiateSceneObject。另一件事是您不需要将实例化的对象转换为 GameObject,因为 photon 已经为您做到了,这与普通的实例化不同。

此外,如果每个游戏室只需要一个盒子,如果您创建一些逻辑以在盒子与玩家碰撞时不破坏盒子,您将能够获得更好的性能。尝试以某种方式对其进行禁用,而不是每次都销毁和恢复它。一个想法是将组件的 enable = false 设置为:Animator、SpriteRenderer、Colliders 等。然后,当玩家放下它时,不要再次实例化它,只需再次打开这些组件,但不要忘记将框的位置更改为你已经在做。

;)

于 2015-06-19T16:59:51.613 回答