Search Unity

Starting Networked Stuff

Discussion in 'Scripting' started by nickavv, Nov 17, 2007.

  1. nickavv

    nickavv

    Joined:
    Aug 2, 2006
    Posts:
    1,801
    Hey guys! I decided to read the documentation and try some networked stuff. So I made a little "game" that lets you instantiate Red and Blue cubes across a network.
    Code (csharp):
    1. var redPrefab : Transform;
    2. var bluePrefab : Transform;
    3. var redSpot : GameObject;
    4. var blueSpot : GameObject;
    5. var hostIP = "---.-.---.--";
    6.  
    7. function OnGUI () {
    8.     if (GUILayout.Button("Create Game")) {
    9.         Network.incomingPassword = "NetPass";
    10.         Network.InitializeServer(32, 25000);
    11.     }
    12.     if (GUILayout.Button("Join Game")) {
    13.         Network.Connect(hostIP, 25000);
    14.     }
    15.     hostIP = GUILayout.TextField(hostIP);
    16.     GUILayout.Label("Enter the Host's IP Address above if Joining a Networked Game");
    17.     if (GUILayout.Button("Begin")) {
    18.         Network.Instantiate(redPrefab, redSpot.transform.position, transform.rotation, 0);
    19.         Network.Instantiate(bluePrefab, blueSpot.transform.position, transform.rotation, 0);
    20.     }
    21. }
    But that's about as far as I got, which works fine over LAN, but not over the internet at all. Also, how would I go about letting each player control one of the cubes? Do I need separate scripts, and is there special code I should put in those scripts and stuff? I just got a little lost is all. Thanks for the help!
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Regarding working over the Internet: The Master Server is there for you. Use it. I know it appears last in the documentation, but IMO you should start with it. It not only handles and hides IP addresses, but also handles NAT punchthrough pretty well which is the big problem when going from LAN to Intertubes.

    For the second, use Network.Instantiate - called by each client when it joins. This client will "own" that object, and you can check for this property and you can say "if (this is mine) { control the object }". If your network view is watching the transform it will move its counterpart are everyone else's machine as well.
     
  3. nickavv

    nickavv

    Joined:
    Aug 2, 2006
    Posts:
    1,801
    Ah, that makes sense. I will look into it. Thank you for being awesome StarManta!