Unity change player PhotonNetwork Room with two object with collider - c#

I'm looking for a solution of the following issue:
I have a player instantiated in lobby room at initial scene. There are two platform objects with colliders, I need to make one platform to join to one room with a scene and other platform to another room with another scene. I have attached the same script for both of platform with a boolean value which determines to which room to join. Instead of determine to which room to join it triggers both scripts. I need to work it in this way:
Platform A:
private bool teleportToShop = true;
If (teleportToShop) -> join shop room
Platform B:
private bool teleportToShop = false;
If (!teleportToShop) -> join event room
Here's my code attached to both game objects:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Portal : MonoBehaviourPunCallbacks
{
[SerializeField] private bool teleportToShop;
private float portalTime = 3f;
private string EVENT_HALL_TAG = "Cinema Hall";
private string LOBBY_TAG = "Lobby";
private string SHOP_TAG = "Shop";
private int currentRoom = 0;
private string nextRoom;
private PhotonView portalView;
private void Awake()
{
portalView = GetComponent<PhotonView>();
}
private void OnTriggerStay(Collider other)
{
if (portalView.IsMine)
{
if (other.GetComponent<PhotonView>().IsMine)
{
if (other.gameObject.tag == "Player")
{
if (portalTime > 0)
{
portalTime -= Time.deltaTime;
}
else
{
portalTime = 3f;
if (SceneManager.GetActiveScene().name == EVENT_HALL_TAG || SceneManager.GetActiveScene().name == SHOP_TAG)
{
currentRoom = 1;
PhotonNetwork.LeaveRoom();
}
else
{
currentRoom = 0;
PhotonNetwork.LeaveRoom();
}
}
}
}
}
}
private void OnTriggerExit(Collider other)
{
portalTime = 3f;
}
public override void OnConnectedToMaster()
{
PhotonNetwork.AutomaticallySyncScene = false;
PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
if (currentRoom == 0)
{
if (!teleportToShop)
{
PhotonNetwork.JoinRoom("EventHallRoom");
}
else if (teleportToShop)
{
PhotonNetwork.JoinRoom("ShopRoom");
}
}
else PhotonNetwork.JoinRoom("LobbyRoom");
}
public override void OnJoinRoomFailed(short returnCode, string message)
{
base.OnJoinRandomFailed(returnCode, message);
if (currentRoom == 0)
{
if (!teleportToShop)
{
PhotonNetwork.CreateRoom("EventHallRoom");
}
else if (teleportToShop)
{
PhotonNetwork.CreateRoom("ShopRoom");
}
}
else PhotonNetwork.CreateRoom("LobbyRoom");
}
public override void OnJoinedRoom()
{
if (currentRoom == 0)
{
if (!teleportToShop)
{
PhotonNetwork.LoadLevel(EVENT_HALL_TAG);
}
else if (teleportToShop)
{
PhotonNetwork.LoadLevel(SHOP_TAG);
}
}
else PhotonNetwork.LoadLevel(LOBBY_TAG);
}
public override void OnLeftRoom()
{
GameManager.currentPlayer = null;
}
}

Related

Unity Photon.Pun Connecting isues When Change Scene

Hello Guys i am working on a small project and I installed the room setup system in the lobby without any problems, and when we set up the room, it directs us to a 2D scene. Everything was exactly what I wanted until now, like the room scene among us. LoadScene("Game"); I added the code and assigned it to the button. When I press the button, the scene changes, but [my status text says connecting but never connected, it's always stuck connecting and therefore players cannot go on stage] I'll share my codes below, can you help me?
Network.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Photon.Pun;
using Photon.Realtime;
public class Network : MonoBehaviourPunCallbacks
{
public Text StatusText;
public CameraFollow playerCamera;
public MasterClient masterClient;
private void Start()
{
StatusText.text = "Connecting";
PhotonNetwork.NickName = "Player" + Random.Range(0, 5000);
// CreatePlayerCamera();
}
public void GameScene()
{
StatusText.text = "Joined " + PhotonNetwork.CurrentRoom.Name;
PhotonNetwork.LoadLevel("Game");
}
private void CreatePlayerCamera()
{
playerCamera.target = PhotonNetwork.Instantiate("Player", new Vector3(
Random.Range(-5, 5),
Random.Range(-5, 5),
0), Quaternion.identity).transform;
if (PhotonNetwork.IsMasterClient)
{
masterClient.Initialize();
}
}
public override void OnConnectedToMaster()
{
StatusText.text = "Connected to Master / Joining room";
PhotonNetwork.JoinOrCreateRoom("GameRoom", new RoomOptions() { MaxPlayers = 4 }, null);
CreatePlayerCamera();
}
public override void OnJoinedRoom ()
{
StatusText.text = PhotonNetwork.CurrentRoom.Name;
playerCamera.target = PhotonNetwork.Instantiate("Player",
new Vector3(
Random.Range(-10, 10),
Random.Range(-10, 10),
0), Quaternion.identity).transform;
}
}
Lobbynetwork.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class LobbyNetworkManager : MonoBehaviourPunCallbacks
{
int number;
int number2;
public Text su;
private List<RoomItemUI> _roomList = new List<RoomItemUI> ();
[SerializeField] private RoomItemUI _roomItemUIPrefab;
[SerializeField] private Transform _roomListParent;
[SerializeField] private Text _statusField;
[SerializeField] private Button _leaveRoomButton;
[SerializeField] private InputField _roomInput;
[SerializeField] private InputField _joinInput;
[SerializeField] private RoomItemUI _playerItemUIPrefab;
[SerializeField] private Transform _playerListParent;
private List<RoomItemUI> _playerList = new List<RoomItemUI>();
private void Start()
{
Initialize();
Connect();
}
#region PhotonCallbacks
public override void OnConnectedToMaster()
{
Debug.Log("Connected to master server");
PhotonNetwork.JoinLobby();
}
public override void OnRoomListUpdate(List<RoomInfo> roomList)
{
UpdateRoomList(roomList);
}
public override void OnDisconnected(DisconnectCause cause)
{
Debug.Log("Disconnect");
}
public override void OnJoinedLobby()
{
Debug.Log("Joined Lobby!");
}
public override void OnJoinedRoom()
{
_statusField.text = "Joined " + PhotonNetwork.CurrentRoom.Name;
Debug.Log("Joined Room " + PhotonNetwork.CurrentRoom.Name);
MoveScene();
// _leaveRoomButton.interactable = true;
UpdatePlayerList();
}
private void MoveScene()
{
PhotonNetwork.LoadLevel("Room_Scene");
}
public override void OnLeftRoom()
{
_statusField.text = "Lobby";
Debug.Log("Left Room");
_leaveRoomButton.interactable = false;
UpdatePlayerList();
}
public override void OnPlayerEnteredRoom(Player newPlayer)
{
UpdatePlayerList();
}
public override void OnPlayerLeftRoom(Player otherPlayer)
{
UpdatePlayerList();
}
#endregion
private void Initialize()
{
_leaveRoomButton.interactable = false;
}
private void Connect()
{
PhotonNetwork.NickName = "Player" + Random.Range(0, 5000);
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.AutomaticallySyncScene = true;
}
private void UpdateRoomList(List<RoomInfo> roomList)
{
//Clear the current list of rooms
for (int i =0; i < _roomList.Count; i++)
{
Destroy(_roomList[i].gameObject);
}
_roomList.Clear();
// Generate a new list with the updated info
for (int i = 0; i < roomList.Count; i++)
{
//skip empty rooms
if(roomList[i].PlayerCount == 0) { continue; }
RoomItemUI newRoomItem = Instantiate(_roomItemUIPrefab);
newRoomItem.LobbyNetworkParent = this;
newRoomItem.SetName(roomList[i].Name);
newRoomItem.transform.SetParent(_roomListParent);
_roomList.Add(newRoomItem);
}
}
private void UpdatePlayerList()
{
//Clear the current player list
//clear current list of room
for (int i = 0; i < _playerList.Count; i++)
{
Destroy(_playerList[i].gameObject);
}
_playerList.Clear();
if(PhotonNetwork.CurrentRoom == null) { return; }
//Generate a new list of players
foreach(KeyValuePair<int, Player> player in PhotonNetwork.CurrentRoom.Players)
{
RoomItemUI newPlayerItem = Instantiate(_playerItemUIPrefab);
newPlayerItem.transform.SetParent(_playerListParent);
newPlayerItem.SetName(player.Value.NickName);
_playerList.Add(newPlayerItem);
}
}
public void JoinRoom(string roomName)
{
PhotonNetwork.JoinRoom(roomName);
}
public void CreateRoom()
{
number = Random.Range(1000, 9000);
number2 = Random.Range(100, 800);
PhotonNetwork.CreateRoom("Su" + number + "TR" + number2, new RoomOptions() { MaxPlayers = 4 }, null);
/* if (string.IsNullOrEmpty(_roomInput.text) == false)
{
PhotonNetwork.CreateRoom(_roomInput.text + number, new RoomOptions() { MaxPlayers = 4 }, null);
} */
MoveScene();
}
public void JoinWitchCode ()
{
PhotonNetwork.JoinRoom(_joinInput.text);
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
}
}
Check my video
Youtube

How do I fix music in my Unity project which randomly bugs when I run the Gameplay scene?

So I recently finished Sebastian Lague's Create a Game series and everything works fine except for the music. I don't know the cause of issue but while in gameplay scene another theme just starts playing, same thing happens when I restart the game and this also happens in Sebastian's finale version of the game so I can't find the answer there. I didn't really try anything since I don't have an idea what cause of the issue may be, so I decided to write here and maybe someone will know the answer. Thanks in advance!
Audio Manager:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class AudioManager : MonoBehaviour
{
public enum AudioChannel { Master, Sfx, Music };
public float masterVolumePercent { get; private set; }
public float sfxVolumePercent { get; private set; }
public float musicVolumePercent { get; private set; }
private AudioSource sfx2DSource;
private AudioSource[] musicSources;
private int activeMusicSourceIndex;
public static AudioManager instance;
private Transform audioListener;
private Transform playerT;
private SoundLibrary library;
private void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
library = GetComponent<SoundLibrary>();
musicSources = new AudioSource[2];
for (int i = 0; i < 2; i++)
{
GameObject newMusicSource = new GameObject("Music source " + (i + 1));
musicSources[i] = newMusicSource.AddComponent<AudioSource>();
newMusicSource.transform.parent = transform;
}
GameObject newSfx2Dsource = new GameObject("2D sfx source");
sfx2DSource = newSfx2Dsource.AddComponent<AudioSource>();
newSfx2Dsource.transform.parent = transform;
audioListener = FindObjectOfType<AudioListener>().transform;
if (FindObjectOfType<PlayerInput>() != null)
{
playerT = FindObjectOfType<PlayerInput>().transform;
}
masterVolumePercent = PlayerPrefs.GetFloat("master vol", 1);
sfxVolumePercent = PlayerPrefs.GetFloat("sfx vol", 1);
musicVolumePercent = PlayerPrefs.GetFloat("music vol", 1);
}
}
void Update()
{
if (playerT != null)
{
audioListener.position = playerT.position;
}
}
public void SetVolume(float volumePercent, AudioChannel channel)
{
switch (channel)
{
case AudioChannel.Master:
masterVolumePercent = volumePercent;
break;
case AudioChannel.Sfx:
sfxVolumePercent = volumePercent;
break;
case AudioChannel.Music:
musicVolumePercent = volumePercent;
break;
}
musicSources[0].volume = musicVolumePercent * masterVolumePercent;
musicSources[1].volume = musicVolumePercent * masterVolumePercent;
PlayerPrefs.SetFloat("master vol", masterVolumePercent);
PlayerPrefs.SetFloat("sfx vol", sfxVolumePercent);
PlayerPrefs.SetFloat("music vol", musicVolumePercent);
PlayerPrefs.Save();
}
public void PlayMusic(AudioClip clip, float fadeDuration = 1)
{
activeMusicSourceIndex = 1 - activeMusicSourceIndex;
musicSources[activeMusicSourceIndex].clip = clip;
musicSources[activeMusicSourceIndex].Play();
StartCoroutine(AnimateMusicCrossfade(fadeDuration));
}
public void PlaySound(AudioClip clip, Vector3 pos)
{
if (clip != null)
{
AudioSource.PlayClipAtPoint(clip, pos, sfxVolumePercent * masterVolumePercent);
}
}
public void PlaySound(string soundName, Vector3 pos)
{
PlaySound(library.GetClipFromName(soundName), pos);
}
public void PlaySound2D(string soundName)
{
sfx2DSource.PlayOneShot(library.GetClipFromName(soundName), sfxVolumePercent * masterVolumePercent);
}
IEnumerator AnimateMusicCrossfade(float duration)
{
float percent = 0;
while (percent < 1)
{
percent += Time.deltaTime * 1 / duration;
musicSources[activeMusicSourceIndex].volume = Mathf.Lerp(0, musicVolumePercent * masterVolumePercent, percent);
musicSources[1 - activeMusicSourceIndex].volume = Mathf.Lerp(musicVolumePercent * masterVolumePercent, 0, percent);
yield return null;
}
}
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode sceneMode)
{
if (playerT == null)
{
if (FindObjectOfType<PlayerInput>() != null)
playerT = FindObjectOfType<PlayerInput>().transform;
}
}
}
Music Manager:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MusicManager : MonoBehaviour
{
[SerializeField] private AudioClip mainTheme;
[SerializeField] private AudioClip menuTheme;
private string sceneName;
private void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
void PlayMusic()
{
AudioClip clipToPlay = null;
if(sceneName == "Main Menu")
{
if(clipToPlay == null)
clipToPlay = menuTheme;
}
else if(sceneName == "Gameplay")
{
if(clipToPlay == null)
clipToPlay = mainTheme;
}
if(clipToPlay != null)
{
AudioManager.instance.PlayMusic(clipToPlay, 2);
Invoke("PlayMusic", clipToPlay.length);
Debug.Log(clipToPlay.length);
}
}
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode sceneMode)
{
if(sceneName != scene.name)
{
sceneName = scene.name;
Invoke("PlayMusic", .2f);
}
}
}

Despite the name of the file and the name of the class being the same, Unity still can't find the class

Despite the many times I have rewritten the file and made sure the class and the file name match up unity is still saying it can't find the script class. I even made sure all the spelling important words were correct, and it still says it can't find the script class. The name of the file is BasicAI.cs This is what the file looks like.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
public class BasicAI : MonoBehaviour
{
public UnityEngine.AI.NavMeshAgent agent;
public ThirdPersonCharacteracter character;
public enum State {
PATROL,
CHASE
}
public State state;
private bool alive;
//Patrolling
public GameObject[] markers;
private int markerID=0;
public float patrolSpeed=0.0f;
//Chasing
public float chaseSpeed=1f;
public GameObject target;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
character = GetComponent<ThirdPersoncharacter>();
agent.updatePosition = true;
agent.updateRotation = false;
state = BasicAI.State.PATROL;
alive = true;
StartCoroutine("FiniteState");
}
IEnumerator FiniteState()
{
while(alive)
{
switch(state)
{
case State.PATROL:
Patrol();
break;
case State.CHASE:
Chase();
break;
}
yield return null;
}
}
void Patrol()
{
agent.speed = patrolSpeed;
if(Vector3.Distance(this.transform.position, markers[markerID].transform.position) >= 2)
{
agent.setDestionation(markers[markerID].transform.position);
character.move(agent.desiredVelocity, false, false);
}
else if(Vector3.Distance(this.transform.position, markers[markerID].transform.position) <= 2)
{
markerID += 1;
if(markerID>markers.Length)
{
markerID = 0;
}
}
else
{
character.move(Vector3.zero, false, false);
}
}
void Chase()
{
agent.speed = chaseSpeed;
agent.setDestionation(target.transform.position);
character.move(agent.desiredVelocity, false, false);
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
state = basicAI.State.CHASE;
target = other.GameObject;
}
}
}
}

Extending cross platform input not working

I am trying to extend cross platform input in order to make mobile buttons to move a character left and right. What I did was I created two buttons and a script attached to each called MobileMovementButtons.cs. I run the program and the character moves left just fine but not right... I think it has something to do with my Conditional statement..
Here is my Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.EventSystems;
namespace CrossPlatformInput {
public class MobileMovementButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler{
public enum Direction {
Left,
Right
}
public Direction buttonDirection = Direction.Left;
CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis;
private bool rightPressed = false;
private bool leftPressed = false;
void Awake() {
CrossPlatformInputManager.UnRegisterVirtualAxis ("Horizontal");
}
void OnEnable() {
m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis("Horizontal" );
CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis);
}
void Update() {
if (rightPressed) {
m_HorizontalVirtualAxis.Update (1);
}
if (leftPressed) {
m_HorizontalVirtualAxis.Update (-1);
}
if (!leftPressed && !rightPressed){
m_HorizontalVirtualAxis.Update (0);
}
}
public void OnPointerDown(PointerEventData eD) {
if (this.buttonDirection == Direction.Left) {
leftPressed = true;
}
if (this.buttonDirection == Direction.Right) {
rightPressed = true;
}
}
public void OnPointerUp(PointerEventData eD) {
if (this.buttonDirection == Direction.Left) {
leftPressed = false;
}
if (this.buttonDirection == Direction.Right) {
rightPressed = false;
}
}
}
}
And here is the buttons:

Override Function Not Overriding (Csharp)

I am in a game jam and I have been creating a conversion script. I made a base Interact virtual void In Unity in which each interactable will use public override void Interact() and do whatever is needed. My problem is that when I call Interact() in one my scripts only main function is being called and not the overriding function. I am using Unity 2017, Csharp.
Base Interaction Script
using UnityEngine.AI;
using UnityEngine;
public class Interactable : MonoBehaviour {
private NavMeshAgent NavAgent;
private bool isInteracting;
public virtual void MoveToLocation(NavMeshAgent navMesh)
{
isInteracting = false;
this.NavAgent = navMesh;
NavAgent.stoppingDistance = 4;
NavAgent.destination = transform.position;
}
private void Update()
{
if(!isInteracting && NavAgent != null && !NavAgent.pathPending)
{
if(NavAgent.remainingDistance <= NavAgent.stoppingDistance)
{
Interact();
Debug.Log("Moving To Interactable");
isInteracting = true;
}
else
{
isInteracting = false;
}
}
}
public virtual void Interact()
{
Debug.Log("herro");
}
}
NPC Interaction Script
using UnityEngine.UI;
using UnityEngine;
public class NPC : Interactable {
//Setting Up Conversation Var
public string NPCName;
public string[] Conversation;
private int currentConversation;
//Gettig=ng UI
public CanvasGroup ConversationUI;
public Text Title;
public Text Text;
private void Start()
{
currentConversation = 0;
}
public override void Interact()
{
Debug.Log("Interacting With NPC");
//Opening UI
ConversationUI.alpha = 1;
ConversationUI.interactable = true;
ConversationUI.blocksRaycasts = true;
//Setting Up Name
Title.text = NPCName;
Text.text = Conversation[currentConversation];
}
public void NextConv()
{
currentConversation++;
if (currentConversation >= Conversation.Length)
{
ConversationUI.alpha = 0;
ConversationUI.interactable = false;
ConversationUI.blocksRaycasts = false;
}
else if (currentConversation < Conversation.Length)
{
Text.text = Conversation[currentConversation];
}
}
}

Categories