如何在Photon Unity Network中正确实例化游戏对象?

时间:2016-10-28 16:57:04

标签: c# unity3d unity5 photon

    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;      


    }
}
  

此代码附加到播放器预制件并在其中创建2个对象   同一个地方,对所有玩家都是可见的。一个玩家可以移动   这些对象中的一个,无法控制另一个对象和情况   与第二位球员相反。如何制作它只有这样   一个实例化的对象,可以控制(随身携带   所有玩家的另一个剧本?

1 个答案:

答案 0 :(得分:0)

在您的情况下,您需要使用PhotonNetwork.InstantiateSceneObject()实例化SceneObject,然后在需要时在特定播放器上传输所有权。

在PUN包中有一个名为&#34; DemoChangeOwner&#34;的演示。看看吧。

也读过这个帖子,它提供了丰富的信息:http://forum.photonengine.com/discussion/1844/photonnetwork-instantiate

例如,这是MasterClient执行此操作的工作,因此并非所有客户都有权使用。

再见,