如何在Photon Unity网络中正确实例化一个游戏对象
本文关键字:一个 对象 游戏 实例化 Photon Unity 网络 | 更新日期: 2023-09-27 18:15:28
此代码附加到播放器预制件并在同一位置创建2个对象,这两个对象对所有玩家都可见。
一个玩家可以移动其中一个物体,但不能控制另一个,而第二个玩家的情况正好相反。
如何使它只有一个实例化的对象,它可以控制(移动周围与另一个脚本,我有)由所有玩家?
using UnityEngine;
using System.Collections;
public class SpawnGameObjectsNetwork : Photon.MonoBehaviour
{
public float secondsBetweenSpawning = 0.1f;
public float xMinRange = -25.0f;
public float xMaxRange = 25.0f;
public float yMinRange = 8.0f;
public float yMaxRange = 25.0f;
public float zMinRange = -25.0f;
public float zMaxRange = 25.0f;
public float zMinRange2 = 81.0f;
public float zMaxRange2 = 85.0f;
public string spawnObjects;
Vector3 spawnPosition;
Vector3 spawnPosition2;
public float nextSpawnTime;
void Start ()
{
nextSpawnTime = Time.time+secondsBetweenSpawning;
}
void Update()
{
if ( PhotonNetwork.isMasterClient )
{
if ( Time.time > nextSpawnTime )
{
Vector3 spawnPosition;
Vector3 spawnPosition2;
spawnPosition.x = Random.Range (xMinRange, xMaxRange);
spawnPosition.y = Random.Range (yMinRange, yMaxRange);
spawnPosition.z = Random.Range (zMinRange, zMaxRange);
spawnPosition2.x = Random.Range (xMinRange, xMaxRange);
spawnPosition2.y = Random.Range (yMinRange, yMaxRange);
spawnPosition2.z = Random.Range (zMinRange2, zMaxRange2);
GetComponent<PhotonView>().RPC( "MakeThingToSpawn", PhotonTargets.All, spawnPosition, spawnPosition2 );
nextSpawnTime = Time.time + secondsBetweenSpawning;
}
}
}
[PunRPC]
void MakeThingToSpawn( Vector3 spawnPosition, Vector3 spawnPosition2 )
{
GameObject spawnedObject = PhotonNetwork.Instantiate(spawnObjects, spawnPosition, transform.rotation, 0) as GameObject;
GameObject spawnedObject2 = PhotonNetwork.Instantiate(spawnObjects, spawnPosition2, transform.rotation, 0) as GameObject;
}
}
在您的情况下,您需要使用PhotonNetwork.InstantiateSceneObject()实例化一个SceneObject,然后在需要时在特定的播放器上转移所有权。
在PUN包中有一个名为demochangeowner的演示。看一看
也读这个线程,它的信息:http://forum.photonengine.com/discussion/1844/photonnetwork-instantiate
例如,这是MasterClient的工作,所以不是所有的客户端都有资格。