- Home /
Spawning troubles
Does anyone know if there's a way to attach a script to a controller that when you press 'join game' it switches to the controller? I'm using this on a different base.
https://www.youtube.com/watch?v=3jwJiXnqfcs&feature=youtube_gdata_player
Do you have several controllers, or just one? Do you want to switch cameras also, or just start controlling the player? Please, provide a bit more context about your scene and whatever code you have that might have something to do with that.
Just one controller, the main one. And I want it to switch to a lobby cam so when you click 'join game' you switch to the controller in a spawn
Just one controller, the main one. And I want it to switch to a lobby cam so when you click 'join game' you switch to the controller in a spawn
Answer by suribe · Mar 10, 2014 at 01:38 PM
Both things should work kind of similarly. If you have several Cameras on the scene, you should disable all of them except for the one you want active. So first, you should iterate through all, probably by calling
GameObject.FindGameObjectsWithTag
(check the docs on how to use it), and setting enabled = true only for one.
And the same with the controller, you should disable all, or Destroy them, and only leave one. For more details and specifics, please provide some code.
edit
Man, that's a lot of code. :)
You should insert the switching here:
...
if(GUILayout.Button("Join Game", conGUI.customStyles[12], GUILayout.Width(120),
GUILayout.Height(30))) {
if(room.playerCount < room.maxPlayers){
PhotonNetwork.JoinRoom(room.name);
PhotonNetwork.playerName = playerName;
connecting = true;
}
}
...
The code should create the player object, which you should have as a prefab to make it easier. It should already include a Controller, the mesh, animations, etc. You should start with some already made from other example. Something like:
GameObject.Instantiate(Resources.Load<GameObject>("PlayerPrefab"));
Where PlayerPrefab is the prefab you have already set up. If it includes a Controller, and as there seems to be no other in the scene, it should became active. You probably want to change the camera. If you want it first person, then again: preattach it to the PlayerPrefab and set it to active, while setting the others inactive (enabled = false) in the scene.
This should get you started, I think.
I think this is where it went wrong. Theres a prefab named "PlayerPrefab" but where my prefab is named "CODcontroller" I replaced it with that name and hopefully it should work. And they are in the same folder. Heres a screenshot of what error I get and heres the code I think I went wrong on
var spawnPoint : GameObject = allSpawnPoints[Random.Range(0, allSpawnPoints.Length)];
var nPlayer : GameObject = PhotonNetwork.Instantiate("PlayerPrefab", spawnPoint.transform.position, spawnPoint.transform.rotation, 0);
Or maybe where it says 'Spawn points' it was set to 0. I changed the size to 3 and attached them. I also had to attach photonView to the player prefab and tsting now. hopefully it works!
Answer by CodyMoores · Mar 10, 2014 at 09:17 PM
This is the code for the Connection Manager:
class AU_ConnectionManager extends Photon.MonoBehaviour {
private var state : int = 0;
//0 = enter nickname
//1 = main menu
//2 = host game
//3 = join game
//4 = settings
//5 = quit game
private var playerName : String;
private var hostName : String; //Name of room
var conGUI : GUISkin;
//Loading effect
var loadingTexture : Texture;
private var size : float = 50.0;
private var rotAngle : float = 0.0;
private var rotSpeed : float = 1000.0;
private var effectTime : float = 0.3;
private var alpha : float = 2.0;
var clickSound : AudioClip;
var backSound : AudioClip;
var effects : AU_GUI;
//OPTIONS
private var sensitivity : float = 2.0;
private var soundVol : float = 1.0;
private var graphicsQual : int = 5;
private var res : int; //Resolution
private var qual : int = 0;
var sliderBG : Texture;
var sliderThumb : Texture;
var settingsBG : Texture;
var showConnectionStatus : boolean = false;
@HideInInspector
var connecting : boolean = false;
@HideInInspector
var loading : boolean = false;
//SERVERLIST
var roomList : RoomInfo[];
private var listRefreshed : boolean = false;
private var scroll : Vector2;
//Max players in game
var maxPlayers : int[];
private var players : int;
//This is just for example
var exampleCustomProps : int[];
private var num : int;
function Start () {
hostName = "armedunity (" + Random.Range(10, 999) + ")";
playerName = "Guest (" + Random.Range(10, 999) + ")";
PhotonNetwork.isMessageQueueRunning = true;
PhotonNetwork.ConnectUsingSettings("armedunity");
}
function Update () {
if(loading) rotAngle += rotSpeed * Time.deltaTime;
}
function FadeGUI(temp : int){
alpha = 0.0;
state = temp;
loading = true;
while (alpha < 2.0) {
alpha += Time.deltaTime/effectTime;
yield;
}
effects.ShowUp();
loading = false;
}
function OnGUI(){
GUI.skin = conGUI;
//Preoject version
if( state == 0) GUI.Label(Rect (Screen.width - 100, 20, 100, 30), "<b><size=14> Version 0.7 </size></b>");
//Connection status
if(showConnectionStatus) GUI.Label (Rect(0, 10, 500, 20), " <b> Status: " + PhotonNetwork.connectionStateDetailed.ToString() + "</b>", conGUI.customStyles[20]);
if(connecting) {
alpha = 0.0;
loading = true;
}
//Disable GUI functionality when loading (buttons will not work)
if(loading && state != 0) GUI.enabled = false;
else GUI.enabled = true;
//Everything after this line will be affected when we will change "alpha"
GUI.color = Color(1.0,1.0,1.0,alpha);
if( state == 0){
EnterName();
}else if( state == 1){
MainMenu();
}else if( state == 2){
ServerList();
}else if( state == 3){
CreateServer();
}else if( state == 4){
Settings();
}else if( state == 5){
QuitGame();
}
if(state > 1 && state != 5) ButtonBack();
LoadingEffect();
}
function EnterName(){
GUILayout.BeginArea(Rect (Screen.width/2 - 175, Screen.height/2 - 57, 350, 115), "", conGUI.customStyles[0]);
GUILayout.BeginVertical();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.Space(25);
GUILayout.Label("<b><size=16>Name:</size></b>");
GUILayout.Space(20);
GUI.SetNextControlName ("user");
playerName = playerName.Replace("\n", "");
playerName = GUILayout.TextField (playerName, 20, conGUI.customStyles[2], GUILayout.Width(223), GUILayout.Height(25));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(30);
GUILayout.BeginHorizontal();
GUILayout.Space(115);
if(GUILayout.Button("Quit", conGUI.customStyles[1], GUILayout.Width(110), GUILayout.Height(32))){
if(playerName != "" && playerName.length >= 3){
PlayAudioClip(backSound, transform.position, 1.0);
Application.Quit();
}
}
GUILayout.Space(5);
if(GUILayout.Button("Continue", conGUI.customStyles[1], GUILayout.Width(110), GUILayout.Height(32))){
if(playerName != "" && playerName.length >= 3){
PlayAudioClip(clickSound, transform.position, 1.0);
FadeGUI(1);
}
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndArea ();
}
function MainMenu(){
GUILayout.BeginArea (Rect(5, (Screen.height - 235) , 300, 300));
if(GUILayout.Button("", conGUI.customStyles[5] )){
state = 2;
effects.Hide();
PlayAudioClip(clickSound, transform.position, 1.0);
}
if(GUILayout.Button("", conGUI.customStyles[6])){
state = 3;
effects.Hide();
PlayAudioClip(clickSound, transform.position, 1.0);
}
if(GUILayout.Button("",conGUI.customStyles[7])){
state = 4;
effects.Hide();
PlayAudioClip(clickSound, transform.position, 1.0);
}
if(GUILayout.Button("", conGUI.customStyles[8])){
state = 5;
effects.Hide();
PlayAudioClip(clickSound, transform.position, 1.0);
}
GUILayout.EndArea();
}
function CreateServer(){
GUILayout.BeginArea(Rect (Screen.width/2 - 225, Screen.height/2 - 110, 450, 220), "", conGUI.customStyles[10]);
GUI.Box (Rect(30,30,150,30),"Host Name: ");
hostName = hostName.Replace("\n", "");
hostName = GUI.TextField (Rect(200,30,220,30), hostName, 20, conGUI.customStyles[2]);
GUI.Box (Rect(30,70,150,30),"Max Players: ");
if (GUI.Button(Rect(200,70,40,30), "<<", "Box")){
if(players < maxPlayers.length){
players--;
if(players < 0) players = maxPlayers.length - 1;
}
}
GUI.Box(Rect(260,70,100,30), maxPlayers[players].ToString());
if (GUI.Button(Rect(380,70,40,30), ">>", "Box")){
if(players < maxPlayers.length){
players++;
if(players > (maxPlayers.length - 1)) players = 0;
}
}
GUI.Box (Rect(30,110,150,30),"Example: ");
if (GUI.Button(Rect(200,110,40,30), "<<", "Box")){
if(num < exampleCustomProps.length){
num--;
if(num < 0) num = exampleCustomProps.length - 1;
}
}
GUI.Box(Rect(260,110,100,30), exampleCustomProps[num].ToString());
if (GUI.Button(Rect(380,110,40,30), ">>", "Box")){
if(num < exampleCustomProps.length){
num++;
if(num > (exampleCustomProps.length - 1)) num = 0;
}
}
GUILayout.BeginHorizontal();
if(GUI.Button(Rect(290,173,150,35),"Create Game", conGUI.customStyles[1])) {
PhotonNetwork.player.name = playerName;
var gameSettings : ExitGames.Client.Photon.Hashtable = new ExitGames.Client.Photon.Hashtable();
gameSettings["MyString"] = exampleCustomProps[num].ToString();
var properties : String[]= new String[1];
properties[0] = "MyString";
PhotonNetwork.CreateRoom(hostName, true, true, maxPlayers[players], gameSettings, properties);
connecting = true;
}
GUILayout.Space(20);
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
function ServerList () {
GUILayout.BeginArea(Rect (Screen.width/2 - 400, Screen.height/2 - 180, 800, 400), "", conGUI.customStyles[11]);
//Refresh ServerList
if(GUI.Button(Rect(15,10,130,35), "Refresh", conGUI.customStyles[14])) RefreshingList();
GUI.Box(Rect(145,10,140,30), "Host Name", conGUI.customStyles[15]);
GUI.Box(Rect(295,10,140,30), "Map Name", conGUI.customStyles[15]);
GUI.Box(Rect(445,10,130,30), "Game Mode", conGUI.customStyles[15]);
GUI.Box(Rect(585,10,80,30), "Players", conGUI.customStyles[15]);
GUI.Box(Rect(675,10,60,30), "Ping", conGUI.customStyles[15]);
scroll = GUI.BeginScrollView(Rect(15,67,765,315),scroll, Rect (0, 0, 220, 1000), false, true);
if(listRefreshed && !loading){
for ( var room : RoomInfo in roomList){
GUILayout.BeginHorizontal("Label");
if(GUILayout.Button("Join Game", conGUI.customStyles[12], GUILayout.Width(120), GUILayout.Height(30))) {
if(room.playerCount < room.maxPlayers){
PhotonNetwork.JoinRoom(room.name);
PhotonNetwork.playerName = playerName;
connecting = true;
}
}
GUILayout.Box(room.name, conGUI.customStyles[13], GUILayout.Width(150), GUILayout.Height(30));
GUILayout.Box("TestMap", conGUI.customStyles[13], GUILayout.Width(150), GUILayout.Height(30));
GUILayout.Box("CO-OP", conGUI.customStyles[13], GUILayout.Width(140), GUILayout.Height(30));
GUILayout.Box(room.playerCount + "/" + room.maxPlayers, conGUI.customStyles[13], GUILayout.Width(90), GUILayout.Height(30));
GUILayout.Box(PhotonNetwork.GetPing().ToString(), conGUI.customStyles[13], GUILayout.Width(70), GUILayout.Height(30));
GUILayout.EndHorizontal();
}
if(roomList.Length == 0 && !loading) GUI.Label(Rect(320,150,200,30),"<b>No games found!!!</b>");
}
GUI.EndScrollView();
GUILayout.EndArea();
}
function Settings(){
GUILayout.BeginArea(Rect (Screen.width/2 - 250, Screen.height/2 - 170, 500, 250), conGUI.customStyles[16]);
GUILayout.Space(10);
GUILayout.Label("<size=22><b> Settings</b></size>");
GUI.Box (Rect (20, 65, 110, 30), "Volume:", conGUI.customStyles[20]);
soundVol = GUI.HorizontalSlider (Rect (145, 75, 250, 30), soundVol, 0.0, 1.0);
GUI.DrawTexture (Rect (145, 77, soundVol * 250, 7), sliderBG);
GUI.DrawTexture (Rect (145 + (soundVol * 240), 75, 12, 12), sliderThumb);
GUI.Box (Rect (410, 70, 70, 30), soundVol.ToString("F1"));
AudioListener.volume = soundVol;
GUILayout.BeginArea (Rect (20,130,467,225), "");
//Quality
GUILayout.BeginHorizontal("box", GUILayout.Width(460), GUILayout.Height(40));
GUILayout.Label("Quality:", conGUI.customStyles[20], GUILayout.Width(180), GUILayout.Height(40));
GUILayout.Space(20);
var names = QualitySettings.names;
if (GUILayout.Button("", conGUI.customStyles[17], GUILayout.Width(40), GUILayout.Height(40))){
if(qual < names.length){
qual--;
if(qual < 0) qual = names.length - 1;
}
}
GUILayout.Space(5);
if(GUILayout.Button(names[qual], conGUI.customStyles[19], GUILayout.Width(140), GUILayout.Height(40))){
QualitySettings.SetQualityLevel (qual, false);
}
GUILayout.Space(5);
if (GUILayout.Button("", conGUI.customStyles[18], GUILayout.Width(40), GUILayout.Height(40))){
if(qual < names.length){
qual++;
if(qual > (names.length - 1)) qual = 0;
}
}
GUILayout.EndHorizontal();
//Resolution
GUILayout.BeginHorizontal("box", GUILayout.Width(460));
GUILayout.Label("Resolution: ", conGUI.customStyles[20], GUILayout.Width(180), GUILayout.Height(40));
GUILayout.Space(20);
var resolutions : Resolution[] = Screen.resolutions;
if (GUILayout.Button("", conGUI.customStyles[17], GUILayout.Width(40), GUILayout.Height(40))){
if(res < resolutions.length){
res--;
if(res < 0) res = resolutions.length - 1;
}
}
GUILayout.Space(5);
if(GUILayout.Button(resolutions[res].width + "x" + resolutions[res].height, conGUI.customStyles[19], GUILayout.Width(140), GUILayout.Height(40)) || Event.current.type == EventType.keyDown && Event.current.character == "\n"){
Screen.SetResolution (resolutions[res].width, resolutions[res].height, false);
}
GUILayout.Space(5);
if (GUILayout.Button("", conGUI.customStyles[18], GUILayout.Width(40), GUILayout.Height(40))){
if(res < resolutions.length){
res++;
if(res > (resolutions.length - 1)) res = 0;
}
}
GUILayout.EndHorizontal();
GUILayout.EndArea();
GUILayout.EndArea();
}
function QuitGame(){
GUILayout.BeginArea(Rect (Screen.width/2 - 150, Screen.height/2 - 60, 300, 120), "", conGUI.customStyles[3]);
GUILayout.BeginVertical();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
GUILayout.Label("<b>Are you sure you want to exit game?</b>");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(30);
GUILayout.BeginHorizontal();
GUILayout.Space(95);
if(GUILayout.Button("<b>Cancel</b>", conGUI.customStyles[4], GUILayout.Width(90), GUILayout.Height(35))){
FadeGUI(1);
PlayAudioClip(backSound, transform.position, 1.0);
}
GUILayout.Space(10);
if(GUILayout.Button("<b>Yes</b>", conGUI.customStyles[4], GUILayout.Width(90), GUILayout.Height(35))){
PlayAudioClip(clickSound, transform.position, 1.0);
Application.Quit();
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndArea ();
}
function ButtonBack(){
GUILayout.BeginArea (Rect(10, (Screen.height - 80) , 200, 400));
if(GUILayout.Button("", conGUI.customStyles[9])){
PlayAudioClip(backSound, transform.position, 1.0);
listRefreshed = false;
FadeGUI(1);
}
GUILayout.EndArea();
}
function LoadingEffect(){
GUI.color = Color(1.0,1.0,1.0,1.0);
if(loading && state > 0){
var pivot : Vector2 = Vector2(Screen.width -50, Screen.height -50);
GUIUtility.RotateAroundPivot(rotAngle%360,pivot);
GUI.DrawTexture(Rect (Screen.width -50 - (size/2) , Screen.height -50 - (size/2), size, size), loadingTexture);
}
}
function RefreshingList(){
loading = true;
yield WaitForSeconds( 1.0); // To show loading effect
roomList = PhotonNetwork.GetRoomList();
loading = false;
listRefreshed = true;
}
function PlayAudioClip (clip : AudioClip, position : Vector3, volume : float) {
var go = new GameObject ("One shot audio");
go.transform.position = position;
var source : AudioSource = go.AddComponent (AudioSource);
source.clip = clip;
source.volume = volume;
source.Play ();
Destroy (go, clip.length);
return source;
}
///////////////////////////
// Photon Functions ///////////////////////////
function OnConnectedToPhoton () {
Debug.Log ("OnConnectedToPhoton()..... Called when the server is available and before client authenticates.");
connecting = false;
}
function OnJoinedLobby(){
Debug.Log("OnJoinedLobby().... Use a GUI to show existing rooms available in PhotonNetwork.GetRoomList().");
}
function OnReceivedRoomListUpdate(){
Debug.Log("OnReceivedRoomListUpdate()....");
}
function OnCreatedRoom(){
Debug.Log("OnCreatedRoom()....");
}
function OnJoinedRoom () {
Debug.Log("Room: "+ PhotonNetwork.room.name + "_ OnJoinedRoom() called by PUN. Now this client is in a room.");
connecting = true;
PhotonNetwork.isMessageQueueRunning = false;
yield WaitForSeconds(1); // Just to make loading time longer
Application.LoadLevel("PFPSKv0.9");
}
function OnPhotonJoinRoomFailed () {
Debug.Log ("OnPhotonJoinRoomFailed().... Called if a JoinRoom() call failed. Most likely because the room does not exist or the room is full.");
connecting = false;
loading = false;
}
function OnFailedToConnectToPhoton(cause : DisconnectCause){
Debug.LogError("OnFailedToConnectToPhoton()..... Cause: " + cause);
connecting = false;
loading = false;
}
function OnPhotonCreateRoomFailed () {
Debug.Log ("OnPhotonCreateRoomFailed()...... Called if a CreateRoom() call failed. Most likely because the room name is already in use");
connecting = false;
loading = false;
}
}
This is the code for the Game Manager:
public class AU_GameManager extends Photon.MonoBehaviour {
var myCustomProp : String;
var connectedPlayerList : Array = new Array(PhotonPlayer);
private var playerName : String;
var levelCamera : Camera;
var audioListener : AudioListener;
var pv : PhotonView;
var allSpawnPoints : GameObject[];
@HideInInspector
var playerInGame : boolean;
function Awake () {
PhotonNetwork.isMessageQueueRunning = true;
playerName = PhotonNetwork.player.name;
//Example how to use custom properties.
//Set: //var setCustomProp : ExitGames.Client.Photon.Hashtable = new ExitGames.Client.Photon.Hashtable(); //setCustomProp.Add("MyString", myCustomProp); //PhotonNetwork.room.SetCustomProperties(setCustomProp); //Get:
myCustomProp = PhotonNetwork.room.customProperties["MyString"]; }
function SpawnPlayer(){
var spawnPoint : GameObject = allSpawnPoints[Random.Range(0, allSpawnPoints.Length)];
var nPlayer : GameObject = PhotonNetwork.Instantiate("PlayerPrefab", spawnPoint.transform.position, spawnPoint.transform.rotation, 0);
if(playerInGame == false){
nPlayer.GetComponent("PlayerConfig").LocalPlayer();
nPlayer.name = playerName;
LevelCamera(false);
playerInGame = true;
}
}
function LevelCamera(action : boolean){
levelCamera.enabled = action;
audioListener.enabled = action;
}
///////////////////////////
// Photon Functions ///////////////////////////
function OnLeftRoom () {
Debug.Log ("*** OnLeftRoom ()..... Called once the local user left a room.");
LeftRoom();
}
function OnDisconnectedFromPhoton () {
Debug.Log ("*** OnDisconnectedFromPhoton ().... Called after disconnecting from the Photon server. In some cases, other events are sent before OnDisconnectedFromPhoton is called.");
LeftRoom();
}
function LeftRoom(){
PhotonNetwork.isMessageQueueRunning = false;
Application.LoadLevel ("MainMenu");
}
function OnPhotonPlayerConnected () {
Debug.Log("*** OnPhotonPlayerConnected()..... Player Connected.");
}
}
As far as I know that's all you need. If you need another script just let me know and I'll post it. Thanks for your help my friend! Goes a long way!
Your answer
Follow this Question
Related Questions
Photon Instantiate 2 Answers
Is possible to spawn 2d image in photon networking ? 1 Answer
Photon enable/disable objects on all views? 1 Answer
Photon - Loads a level but doesn't spawn player. 1 Answer
Unity photon multiplayer teams 3 Answers