The goal of this lab is to create a very simple shared virtual environment using Unity's networking support.
GameObject (GameObject→CreateEmpty) and name it “NetworkManager”. Create a new C# script called “Networking.cs” and attach it to this new game object. Paste the following code into this script:using UnityEngine; using System.Collections; public class Networking : MonoBehaviour { public GameObject playerPrefab; public Transform spawnObject; bool initialized = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnGUI() { if(!initialized) { if(GUI.Button (new Rect(10,10,100,30),"Start Server")) { Network.InitializeServer(32,2500,true); } if(GUI.Button (new Rect(10,100,100,30),"Start Client")) { Network.Connect ("127.0.0.1",2500); } } } void OnServerInitialized() { initialized = true; Debug.Log ("Server Initialized"); spawnPlayer(); } void OnConnectedToServer() { initialized = true; spawnPlayer(); } void spawnPlayer() { Network.Instantiate(playerPrefab, spawnObject.position, Quaternion.identity,0); } }
CharacterMotor component to it (Component→Character→CharacterMotor). Add a NetworkView component to it (Component→Miscellaneous→NetworkView). Create a new C# script called “CharacterMovement.cs” and add the following code to it:using UnityEngine; using System.Collections; public class CharacterMovement : MonoBehaviour { public float speed = 5.0f; public float gravity = 5.0f; private CharacterController cc; // Use this for initialization void Start () { cc = GetComponent<CharacterController>(); } // Update is called once per frame void Update () { if(networkView.isMine) { cc.Move (new Vector3(Input.GetAxis ("Horizontal")*speed*Time.deltaTime, -gravity*Time.deltaTime, Input.GetAxis("Vertical")*speed*Time.deltaTime)); } } }
NetworkedPlayer object into the project panel to create a Prefab and delete the original instance in the Hierarchy view.NetworkManager and drag the NetworkPlayer PreFab into the Player Prefab property and drag the SpawnObject game object into the Spawn Object property.