- Home /
How to Instance GameObjects Over the Pun Network
Hello, I have a script that spawns enemies in a wave based fashion but I am having trouble figuring out how to instance my enemy gameobjects over the pun network. I already have the Photon view and everything on the gameobject but i'm not sure how to actually instance it over the network so other player can see the enemies. My current code for spawning enemies is this:
GameObject instance = (GameObject)Instantiate (zombieEnemy2, near [spawnPointIndex].position, near [spawnPointIndex].rotation);
instance.transform.Rotate (Vector3.up, Random.Range (0f, 360f));
When spawning a prefab, you need to use PhotonNetwork.Instantiate. Heres how it works:`GameObject myPlayer = PhotonNetwork.Instantiate(playerPrefab.name, new Vector3(0f, 0.5f, 0f), Quaternion.identity, 0);`
Pay attention to how you use playerPrefab.name. You need to assign the name of the prefab. Also make sure that a photonView and photonTransformView is assigned to the enemy prefab. If you want more guidelines on this, check out the official PUN networking tutorial documentation.
Answer by Captain_Pineapple · Jul 26, 2020 at 08:51 AM
well there are multiple questions that come up here: what do you do with the zombies? Are they also synced by position? if yes they have a PhotonView and you must use PhotonNetwork.Instantiate.
If you use some other sync method (which i'd highly recommend) the your spawner script needs some kind of RPC. So your spawn function SpawnZombie
gust gets an extra argument, say int spawnIndex
and the one player (most probably the master client) should call the function:
photonView.RPC("SpawnZombie", RpcTarget.All, hereGoesTheNumberOfYourSpawn);
This will the call the named function on ALL players currently connected to your room.
Assuming that your function is:
[PunRPC]
public void SpawnZombie(int spawnIndex)
{
GameObject instance = (GameObject)Instantiate (zombieEnemy2, near [spawnIndex].position, near [spawnIndex].rotation);
}
As you might notice i removed the rotate part from the code since that would not be synced with the current version. So for the random rotation you have to add another argument to the RPC so that the random rotation is decided once for all players by the player why calls the RPC.
Let me know if that helped/if something was unclear.
Answer by Bioman75 · Jul 27, 2020 at 12:34 AM
Okay after tweaking some things your answer works. Thank you :)
Your answer
Follow this Question
Related Questions
Photon Network, how to spawn FPSController from Unity Standard Assets? 2 Answers
Photon Networking: How to spawn my players at the another places? 2 Answers
Unity PhotonNetwork globally enable a component 1 Answer
Only host client is able to spawn objects 0 Answers
[Photon]Player vs. Player Collision 0 Answers