Creating a player

What do i have to do to create a multiplayer player copy? I used some unity network tutorials, but they didnot help. Using C#.

With that script attached to your prefab, the easiest way to instantiate a network-aware object is with a call to Network.Instantiate(). Make sure there is also a NetworkView Component attached to that object, that it observes the script and that it’s State Synchronization mode is set to something other than ‘off’.

While easy it doesn’t allow for much flexibility. Another approach is using an RPC to instantiate the object. This requires you to manually assign it a viewID however, using Network.AllocateViewID(). Keep in mind that the NetworkPlayer who allocated the viewID of an object is the owner of that object, which means several things:

  • He’s the one for whom stream.isWriting will return true.
  • He’s the one for whom networkView.isMine will return true.
  • He’s the only one who can send RPC via that NetworkView.

A simple example for instantiating a network-aware prefab with RPC (c#):

using UnityEngine;

public class NetworkInstantiator : MonoBehaviour
{
	//this is the prefab we'll instantiate; it will have a NetworkView componenet attached so it can receive network updates
	public Transform NetworkAwarePrefab;
	
	void OnGUI()
	{
		//this will use the built-in functionality to instantiate the network-aware prefab, with the player who called this method as the owner
		if (GUILayout.Button("Use Network.Instantiate"))
		{
			Network.Instantiate(NetworkAwarePrefab, Vector3.zero, Quaternion.identity, 0);
		}

		//this will use a custom RPC to instantiate the the network-aware prefab and manually set the player who called this method as the owner
		if (GUILayout.Button("Use Custom RPC"))
		{
			//send the call to CustomInstantiate to all players and make it buffered so that players who later join the game will also receive it
			networkView.RPC("CustomInstantiate", RPCMode.AllBuffered, Network.AllocateViewID());
		}
	}

	/// <summary>
	/// this method will instantiate the network aware prefab and allocate it a new viewID to set the player who instantiated it as the owner
	/// </summary>
	/// <param name="manuallyAllocatedViewID">the viewID allocated by the player who called this method</param>
	[RPC]
	void CustomInstantiate(NetworkViewID manuallyAllocatedViewID)
	{
		//instantiate the prefab and store a reference to it so we can change it's viewID
		var o = Instantiate(NetworkAwarePrefab, Vector3.zero, Quaternion.identity) as Transform;

		//change the viewID of the instantiated object to the one we allocated when the method was called
		o.networkView.viewID = manuallyAllocatedViewID;
	}
}