- Home /
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;
}
}
}
Your answer
Follow this Question
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