Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by HuskyPanda213 · Sep 11, 2013 at 06:11 PM · networkingbugfps

Problems With Networking.

My networked game runs ok the first time I start and connect to a server(though the team kill thing does not work). Though if you disconnect you get 3 instances of the network game object, also if you connect to a server as a client you are in the level but cannot spawn. You also still get the extra network objects. EDIT: I did not fix it but I think something is Wrong with the DontDestroyOnLoad. Please still try and help me fix all the bugs!!!!

Please HELP!

Code Network Object:

using UnityEngine; using System.Collections;

public class NetworkMenu : MonoBehaviour {

 public int leveltoload;
 
 public int port = 24545;
 public string servername = "Server";
 
 public string menu;
 
 public string gameName = "FPS_Assualt";
 
 public string currentLevel;
 
 public static NetworkMenu instance;
 
 public bool matchstarted;
 
 public bool PlayerSpawned;
 
 public GameObject Playerprefab;
 
 public bool Authenticated;
 
 
 public string playername;
 
 
 
 //TEAMS
 
 public int team = 0;
 public string[] teammembers1;
 public string[] teammembers2;
     
 void Awake(){
     instance = this;
     DontDestroyOnLoad(gameObject);
     port = Random.Range(20000,25000);
     playername = "Player";
 /*    Social.localUser.Authenticate (success => {
     if (success) {
         Debug.Log ("Authentication successful");
         string userInfo = "Username: " + Social.localUser.userName + 
             "\nUser ID: " + Social.localUser.id + 
             "\nIsUnderage: " + Social.localUser.underage;
         Debug.Log (userInfo);
         Authenticated = true;
         playername = Social.localUser.userName;
     }
     else{
         Debug.Log ("Authentication failed");
         Authenticated = false;
         }
     });*/
     Authenticated = true;
 }
 
 void Start(){
     NextMenu("Main");    
 }
 
 void OnGUI(){
 //For if the player is connected to a game.
 if(!Network.isClient || !Network.isServer){
 if(Authenticated){
 if(menu == "Main"){
 Menu_Main();        
 }
 if(menu == "Host"){
 Menu_Host();        
 }    
 if(menu == "List"){
 Menu_List();        
 }    
 }//End of Connection If.
 if(menu == "Lobby"){
 Menu_Lobby();        
 }
 }
 else{
 GUI.Label(new Rect(Screen.width / 2 - 200,Screen.height / 2 - 15,400,30),"Please Log-in to gamecenter or restart the app.");        
 }
 }
 
 void SetLevelInComment(){
     if(leveltoload == 1){
         currentLevel = "Test Level";
     }
 }
 
 
 private void Menu_Main(){
     if(GUI.Button(new Rect(10,10,200,25),"Find Servers")){
         NextMenu("List");
     }
     if(GUI.Button(new Rect(10,40,200,25),"Host")){
         NextMenu("Host");
     }
     if(GUI.Button(new Rect(10,70,200,25),"Quit")){
         Application.Quit();
     }
 }
 
 private void Menu_Host(){
     if(GUI.Button(new Rect(10,10,200,25),"Start Server")){
     servername = playername + "'s Server";
     Startserver(servername,port,currentLevel);
     NextMenu("Lobby");
     }
     GUI.Box(new Rect(10,40,200,25),playername + "'s Server");
     if(GUI.Button(new Rect(10,70,200,25),"Back")){
         NextMenu("Main");
     }
 }
 
 private void Menu_List(){
     if(GUI.Button(new Rect(10,10,200,25),"Refresh")){
         MasterServer.RequestHostList(gameName);
     }
     if(GUI.Button(new Rect(10,40,200,25),"Back")){
         NextMenu("Main");
     }
     
     GUILayout.BeginArea(new Rect(Screen.width / 2,0,Screen.width / 2,Screen.height),"Servers","box");
     foreach(HostData hd in MasterServer.PollHostList()){
     GUILayout.Space(25);
     GUILayout.BeginHorizontal();
     
     GUILayout.Label(hd.gameName);
     GUILayout.Label(hd.comment);
 //    GUILayout.Label(hd.connectedPlayers +"/"+ hd.playerLimit);
     if(GUILayout.Button("Connect")){
         Network.Connect(hd);
         NextMenu("Lobby");
     }
     
     GUILayout.EndHorizontal();
     }
     
     GUILayout.EndArea();
 }
 
 public string gu1;
 private void Menu_Lobby(){
     //For things only the host controls
     if(Network.isServer){
         if(!matchstarted){
         if(GUI.Button(new Rect(10,10,200,25),"Start Match")){
         networkView.RPC("AllLoadLevel",RPCMode.AllBuffered,leveltoload);
     //    matchstarted = true;
         Network.maxConnections = 0;
         }
         }
     }
     //For everyone
     if(!matchstarted){
     if(!Network.isServer || !Network.isClient){

     }
     }
     else{
     if(!Network.isServer || !Network.isClient){

     }
     }
     
     
     
     //Spawning Menu
     
     if(matchstarted && team == 0){
     if(!PlayerSpawned && Application.loadedLevel != 0){
         if(GUI.Button(new Rect(10,10,200,25),"Blue")){
         team = 1;
         networkView.RPC("PlayerTeamJoined",RPCMode.All,playername,team);
         }    
         if(GUI.Button(new Rect(10,40,200,25),"Red")){
         team = 2;
         }
     }    
     }
     
     if(matchstarted && team != 0){
         if(!PlayerSpawned && Application.loadedLevel != 0){
         if(GUI.Button(new Rect(10,10,100,25),"SMG Level 1")){
             gu1 = "SMG_1";
         }
         if(gu1 != ""){        
         if(GUI.Button(new Rect(10,40,200,25),"Spawn")){
             SpawnPlayer(gu1,team);
             PlayerSpawned = true;
         }
         }
         }
     }
     }
 
     void SpawnPlayer(string gun1, int _team){
     GameObject[] spawnpoint = GameObject.FindGameObjectsWithTag("Spawnpoint");
     GameObject spawn = spawnpoint[Random.Range(0,spawnpoint.Length)];
     GameObject PLSpawn = Network.Instantiate(Playerprefab,spawn.transform.position,Quaternion.identity,1) as GameObject;
     PLSpawn.GetComponent<NetworkedPlayer>().primary = gun1;
     PLSpawn.GetComponent<NetworkedPlayer>().team = _team;
     PLSpawn.networkView.RPC("SetPrimary",RPCMode.All,gun1);
     }
 
 //Non-RPC server stuff
 
 void OnPlayerConnected(NetworkPlayer player){
 }
 
 void OnPlayerDisconnected(NetworkPlayer pl){
     Network.DestroyPlayerObjects(pl);
 }
 
 void OnDisconnectedFromServer(){

// Network.Disconnect(); MasterServer.RequestHostList(gameName); Application.LoadLevel(0); // Network.Destroy(gameObject,1); // Network.Instantiate(gameObject,Vector3.zero,Quaternion.identity); }

 //Start the Server
 public void Startserver(string _gamename, int _gameport, string level){
     Network.InitializeServer(15,port,false);
     MasterServer.RegisterHost(gameName,_gamename,level);
     Debug.Log("Server Started port: " + _gameport + " Name: " + _gamename);
 }
 
 
 //To set the GUI
 void NextMenu(string to){
     menu = to;
 }
 
 
 [RPC]
 void PlayerTeamJoined(string name,int team){
     
 }
 
 
 [RPC]
 void AllLoadLevel(int levelforloading){
 Network.SetLevelPrefix(levelforloading);
 matchstarted = true;
 Application.LoadLevel(levelforloading);
 }

}

Code Player:

using UnityEngine; using System.Collections; using System.Collections.Generic;

public class NetworkedPlayer : MonoBehaviour {

 public Transform ControllerTransform;

 public GameObject OutsideView;

 public Vector3 CurrentPosition;
 public Quaternion CurrentRotation;
 
 public float health = 100;
 
 public bool alive;
 
 public bool isReloading;
 
 public bool paused;
 
 public string primary;

 public List<TP_Gun> TPguns1 = new List<TP_Gun>();
 
 public List<Gun> FPguns1 = new List<Gun>();
 
 
 
 //TEAMS
 
 public int team;
 
 // Use this for initialization
 void Start () {
 health = 100;
 alive = true;
     
 if(networkView.isMine){
 ControllerTransform.gameObject.SetActive(true);
 OutsideView.SetActive(false);
 }
 else{
 OutsideView.SetActive(true);
 ControllerTransform.gameObject.SetActive(false);
 }
 SetgunFPprimary(primary);
 SetArmColor(team);
 }
 
 private void SetArmColor(int colorTeam){
 foreach(Gun gu in FPguns1){
 gu.myTeam = colorTeam;
 gu.gameObject.GetComponent<FP_TeamColor>().SetColor(colorTeam);
 }
 }
 
 
 // Update is called once per frame
 void Update () {
 if(Input.GetKeyUp(KeyCode.Escape)){
 paused = !paused;        
 }
 }
 
 private void PauseMenu(){
 
 if(paused){
     if(networkView.isMine){
             if(GUI.Button(new Rect(Screen.width / 2 - 100,Screen.height / 2 - 30,200,25),"Resume")){
                 paused = false;
             }
             
             if(GUI.Button(new Rect(Screen.width / 2 - 100,Screen.height / 2,200,25),"Leave")){
                 Network.Disconnect();
                 Application.LoadLevel(0);
             }
             
         }
     }
 }
 
 void OnGUI(){
     if(networkView.isMine){
     if(!alive){
         if(GUI.Button(new Rect(10,10,100,25),"SMG Level 1")){
             primary = "SMG_1";
         }
         //if(primary == ""){    
         if(GUI.Button(new Rect(10,40,200,25),"Respawn")){
             GameObject[] spawnpoint = GameObject.FindGameObjectsWithTag("Spawnpoint");
             GameObject spawn = spawnpoint[Random.Range(0,spawnpoint.Length)];
             gameObject.transform.position = spawn.transform.position;
             alive = true;
             primary = "SMG_1";
             networkView.RPC("Player_Alive",RPCMode.All);
             
             SetgunFPprimary(primary);
             networkView.RPC("SetPrimary",RPCMode.All,primary);
         }
         //}
     }
     else{
     PauseMenu();        
     }
     }
 }
 
 public void SetgunFPprimary(string gun){
     foreach(Gun gu in FPguns1){
         if(gu.Name == primary){
         gu.gameObject.SetActive(true);
         }
         else{
         gu.gameObject.SetActive(false);
         }
     }
 }
 
 [RPC]
 void Server_TakeDamage(float Damage,int hitterteam){
     if(hitterteam != team){
     networkView.RPC("Client_TakeDamage",RPCMode.Server,Damage);
     }
 }
 
 [RPC]
 void Client_TakeDamage(float Damage){
     health -= Damage;
     Debug.Log("Player Has Been Shot!  " + health);
     if(health <= 0){
         networkView.RPC("Player_Dead",RPCMode.All);
         alive = false;
         //Instantiate(Ragdoll,ThirdPerson.position,ThirdPerson.rotation);
     }
         
 }
 
 void FixedUpdate()
 {
     if (networkView.isMine)
     {
         CurrentPosition = ControllerTransform.position;
         CurrentRotation = ControllerTransform.rotation;
     }
     else
     {
         OutsideView.transform.position = CurrentPosition + new Vector3(0,-0.9f,0);
         OutsideView.transform.rotation = CurrentRotation;
     }
 }

 void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
 {
     if (stream.isWriting)
     {
         stream.Serialize(ref CurrentPosition);
         stream.Serialize(ref CurrentRotation);
     }
     else
     {
         stream.Serialize(ref CurrentPosition);
         stream.Serialize(ref CurrentRotation);
     }   
 }
 
 [RPC]
 void Player_Dead(){
     OutsideView.SetActive(false);
     ControllerTransform.gameObject.SetActive(false);
     
 }
 
 [RPC]
 void Player_Alive(){
     health = 100;
     if(networkView.isMine){
         ControllerTransform.gameObject.SetActive(true);
         OutsideView.SetActive(false);
     }
     else{
         OutsideView.SetActive(true);
         ControllerTransform.gameObject.SetActive(false);
     }
 }
 
 
 [RPC]
 void SetPrimary(string item){
     if(!networkView.isMine){
         foreach(TP_Gun g1 in TPguns1){
             if(g1._name == item){
                 g1.gameObject.SetActive(true);
             }
             else{
                 g1.gameObject.SetActive(false);
             }
         }
     }
 }

}

Code Gun:

using UnityEngine; using System.Collections; using System.Collections.Generic;

//[RequireComponent (typeof (NetworkView))]

public class Gun : MonoBehaviour {

 public string Name = "New Weapon";
 public float FireRate;
 public float MinDamage = 25;
 private float Firetime;
 public float Range = 750;
 
 public bool isAuto = false;
 
 public bool TouchInput = false;
 
 public string shootAnimName = "Shoot";
 public string shootAnimName2 = "Shoot2";
 
 public Transform SpawnPoint;
 public Transform muzzleSpawnPoint;
 public int shoot;
 
 public GameObject muzzleflare;
 
 public int AmmoInclip = 30;
 public int Maxclip = 30;
 public int OtherAmmo = 4;
 
 public bool isReloading;
 
 public bool iosShootDown;
 
 public string reloadAnim;
 
 public float reloadtime = 1.5f;
 
 //public GameObject Father;
 
 public GameObject UntaggedHitPartical;
 
 public GameObject Playerhitparticle;
 
 public float AccuracyPlus = 2;
 
 public float AccuracyMinus = 3;
 
 
 
 public int myTeam;
 
 // Use this for initialization
 void Start () {

// Father = GameObject.FindGameObjectWithTag("Player"); muzzleflare = Resources.Load("Prefabs/Muzzleflare") as GameObject; Playerhitparticle = Resources.Load("Prefabs/particle_blood") as GameObject; UntaggedHitPartical = Resources.Load("Prefabs/particle_dirt") as GameObject; }

 // Update is called once per frame
 void Update () {

/* if(!TouchInput){ if(isAuto){ if(Input.GetButton("Fire1")) Fire(); } if(!isAuto){

 }
 }*/
 //for ios    
 if(TouchInput){
 Fire();        
 }
 }
 
 
 void OnGUI()
 {
     if(networkView.isMine){
     if(TouchInput){
     if(GUI.RepeatButton(new Rect(Screen.width - 130,Screen.height - 130,50,50),"Shoot")){
     iosShootDown = true;        
     }
     else{
     iosShootDown = false;        
     }
     if(AmmoInclip < Maxclip){
     if(OtherAmmo > 0){
     if(GUI.Button(new Rect(Screen.width - 55,Screen.height - 240,50,50),"R")){
     StartCoroutine("reload");                
     }            
     }    
     }
     }
     }
 }
 
 
 public void Fire(){
 /*    //FirstPersonAnimations FPA = Father.GetComponent<FirstPersonAnimations>();
     //if(FPA.walkingstate != movecur.run){
     if(!TouchInput){
     if(Firetime <= Time.time){
         
         Firetime = FireRate + Time.time;
         audio.Play();
         shoot = Random.Range(0,2);
         if(shoot == 1){
         gameObject.animation.Play(shootAnimName);
         }
         else{
         gameObject.animation.Play(shootAnimName2);    
         }
         RaycastHit hit;
         Vector3 spawnpos = new Vector3(SpawnPoint.position.x + Random.Range(AccuracyPlus,AccuracyMinus),SpawnPoint.position.y + Random.Range(AccuracyPlus,AccuracyMinus),SpawnPoint.position.z);
         if(Physics.Raycast(SpawnPoint.position,SpawnPoint.forward,out hit,Range)){
         Quaternion rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
         NetworkedPlayer playerm = hit.transform.root.GetComponent<NetworkedPlayer>();
         if(playerm != null){
         playerm.networkView.RPC("Server_TakeDamage",RPCMode.All,MinDamage);    
         Network.Instantiate(Playerhitparticle, hit.point, rot,1);
         }
         else{
         Network.Instantiate(UntaggedHitPartical, hit.point, rot,1);
         }
     //    Network.Instantiate(UntaggedHitPartical, hit.point, rot,1);
         }
         Network.Instantiate(muzzleflare,muzzleSpawnPoint.position,muzzleflare.transform.rotation,1);
     }
     //}
     }*/
     if(TouchInput){
     if(iosShootDown){
     if(AmmoInclip > 0 && !isReloading){
     if(Firetime <= Time.time){
         
         Firetime = FireRate + Time.time;
         audio.Play();
         shoot = Random.Range(0,2);
         if(shoot == 1){
         gameObject.animation.Play(shootAnimName);
         }
         else{
         gameObject.animation.Play(shootAnimName2);    
         }
         RaycastHit hit;
         Vector3 spawnpos = new Vector3(SpawnPoint.position.x + Random.Range(AccuracyPlus,AccuracyMinus),SpawnPoint.position.y + Random.Range(AccuracyPlus,AccuracyMinus),SpawnPoint.position.z);
         if(Physics.Raycast(SpawnPoint.position,SpawnPoint.forward,out hit,Range)){
         Quaternion rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
         NetworkedPlayer playerm = hit.transform.root.GetComponent<NetworkedPlayer>();    
         if(playerm != null){
         playerm.networkView.RPC("Server_TakeDamage",RPCMode.All,MinDamage,myTeam);    
         Network.Instantiate(Playerhitparticle, hit.point, rot,1);
     //    if(playerm.team == myTeam){
     //    Debug.Log("Hit a team member");                    
     //    }
     //    Debug.LogWarning("Hit : " + playerm.team);
         }
         else{
         Network.Instantiate(UntaggedHitPartical, hit.point, rot,1);
         }
     //    Network.Instantiate(UntaggedHitPartical, hit.point, rot,1);
         }
         Network.Instantiate(muzzleflare,muzzleSpawnPoint.position,muzzleflare.transform.rotation,1);
         AmmoInclip--;
     }
     }
     }
     }
 }
 
 
 IEnumerator reload(){
     isReloading = true;
     animation.Play(reloadAnim);
     yield return new WaitForSeconds(reloadtime);
     isReloading = false;
     AmmoInclip = Maxclip;
     OtherAmmo--;
 }

}

Code Team color manager:

using UnityEngine; using System.Collections;

public class FP_TeamColor : MonoBehaviour {

// public int _Playerteam;

 public GameObject arm;
 public GameObject toparm;
 
 //Blue is 1, Red is 2
 public void SetColor(int team){
 if(team == 1){
 arm.renderer.material.color = Color.blue;
 toparm.renderer.material.color = Color.blue;
 }
 if(team == 2){
 arm.renderer.material.color = Color.red;
 toparm.renderer.material.color = Color.red;
 }
 
 }
 

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

15 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Making a FPS, my gun floats sideways in front of me? 1 Answer

Networking question 1 Answer

How do you add a fixed joint to a first person controller 1 Answer

setup a php master server 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges