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
Related
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;
}
}
I've created a leveling system for my game in Unity. I was able to store the level and XP amount in my Firebase database. I'm also able to display both the level and XP in gave and have it update in the database without having to manually save the data.
The problem is now that the xp bar I created that scales based on the amount of xp the user is not communicating with my database, only its self. It also resets all int variables to 0 when switching scenes or restarting the game.
My goal here is to have the progress bar update live based on the amount of xp that's stored in my database and to have it not reset after I switch scenes or reload the game.
Here's my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class LevelSystem
{
public event EventHandler OnExperienceChanged;
public event EventHandler OnLevelChanged;
private static readonly int[] experiencePerLevel = new[] {100, 120, 145, 175, 210, 250, 295, 345, 400, 460};
private int level;
private int experience;
private int experienceToNextLevel;
private TMP_Text xpText;
public LevelSystem()
{
level = 0;
experience = 0;
experienceToNextLevel = 100;
}
public void AddExperience(int amount)
{
if (!IsMaxLevel())
{
experience += amount;
while (!IsMaxLevel() && experience >= GetExperienceToNextLevel(level))
{
//Enough experience to level up
level++;
experience -= GetExperienceToNextLevel(level);
if(OnLevelChanged != null) OnLevelChanged(this, EventArgs.Empty);
}
if(OnExperienceChanged != null) OnExperienceChanged(this, EventArgs.Empty);
}
}
public int GetLevelNumber()
{
return level;
}
public int GetXpAmount()
{
return experience;
}
public float GetExperienceNormalized()
{
if (IsMaxLevel())
{
return 1f;
}
else
{
return (float)experience / GetExperienceToNextLevel(level);
}
}
public int GetExperience()
{
return experience;
}
public int GetExperienceToNextLevel()
{
return experienceToNextLevel;
}
public int GetExperienceToNextLevel(int level)
{
if (level < experiencePerLevel.Length)
{
return experiencePerLevel[level];
}
else
{
//Level invalid
Debug.Log("Level invalid: " + level);
return 100;
}
}
public bool IsMaxLevel()
{
return IsMaxLevel(level);
}
public bool IsMaxLevel(int level)
{
return level == experiencePerLevel.Length - 1;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Utilities.Mine;
public class LevelSystemAnimation
{
public event EventHandler OnExperienceChanged;
public event EventHandler OnLevelChanged;
private LevelSystem levelSystem;
private bool isAnimating;
private float updateTimer;
private float updateTimerMax;
private int level;
private int experience;
public LevelSystemAnimation(LevelSystem levelSystem)
{
SetLevelSystem(levelSystem);
updateTimerMax = .016f;
FunctionUpdater.Create(() => Update());
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
level = levelSystem.GetLevelNumber();
experience = levelSystem.GetExperience();
levelSystem.OnExperienceChanged += LevelSystem_OnExperienceChanged;
levelSystem.OnLevelChanged += LevelSystem_OnLevelChanged;
}
private void LevelSystem_OnLevelChanged(object sender, System.EventArgs e)
{
isAnimating = true;
}
private void LevelSystem_OnExperienceChanged(object sender, System.EventArgs e)
{
isAnimating = true;
}
public void Update()
{
if(isAnimating)
{
updateTimer += Time.deltaTime;
while (updateTimer > updateTimerMax)
{
updateTimer -= updateTimerMax;
UpdateTypeAddExperience();
}
}
}
private void UpdateTypeAddExperience()
{
if(level < levelSystem.GetLevelNumber())
{
//Local level under target level
AddExperience();
}
else
{
//Local level equals the target level
if (experience < levelSystem.GetExperience())
{
AddExperience();
}
else
{
isAnimating = false;
}
}
}
public void AddExperience()
{
experience++;
if (experience >= levelSystem.GetExperienceToNextLevel(level))
{
level++;
experience = 0;
if(OnLevelChanged != null) OnLevelChanged(this, EventArgs.Empty);
}
if(OnExperienceChanged != null) OnExperienceChanged(this, EventArgs.Empty);
}
public int GetLevelNumber()
{
return level;
}
public int GetXpAmount()
{
return experience;
}
public float GetExperienceNormalized()
{
if (levelSystem.IsMaxLevel(level))
{
return 1f;
}
else
{
return (float)experience / levelSystem.GetExperienceToNextLevel(level);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class LevelFunction : MonoBehaviour
{
public static LevelFunction instance;
[SerializeField]
private TMP_Text levelText;
[SerializeField]
private Image experienceBarImage;
[SerializeField]
private TMP_Text xpText;
private LevelSystem levelSystem;
private LevelSystemAnimation levelSystemAnimation;
private void SetExperienceBarSize(float experienceNormalized)
{
experienceBarImage.fillAmount = experienceNormalized;
}
private void SetLevelNumber(int levelNumber)
{
levelText.text = "L" + (levelNumber + 1);
}
private void SetXpAmount(int xpAmount)
{
xpText.text = "" + xpAmount;
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
}
public void SetLevelSystemAnimation(LevelSystemAnimation levelSystemAnimation)
{ //Set the LevelSystem object
this.levelSystemAnimation = levelSystemAnimation;
//Update the starting values
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
//Subscribe to the chnaged events
levelSystemAnimation.OnExperienceChanged += LevelSystemAnimation_OnExperienceChanged;
levelSystemAnimation.OnLevelChanged += LevelSystemAnimation_OnLevelChanged;
}
private void LevelSystemAnimation_OnLevelChanged(object sender, System.EventArgs e)
{
//Level changed, update text
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
}
private void LevelSystemAnimation_OnExperienceChanged(object sender, System.EventArgs e)
{
//Experience changed, update bar size
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class GainXpManager : MonoBehaviour
{
public static GainXpManager instance;
[SerializeField]
private Button collectButton;
[SerializeField]
private TMP_Text levelText;
[SerializeField]
private Image experienceBarImage;
[SerializeField]
private TMP_Text xpText;
public GameObject endGameResults;
private LevelSystem levelSystem;
private LevelSystemAnimation levelSystemAnimation;
private int level;
private int experience;
private void SetExperienceBarSize(float experienceNormalized)
{
experienceBarImage.fillAmount = experienceNormalized;
}
private void SetLevelNumber(int levelNumber)
{
levelText.text = "L" + (levelNumber + 1);
}
private void SetXpAmount(int xpAmount)
{
xpText.text = "" + xpAmount;
}
public void SetLevelSystem(LevelSystem levelSystem)
{
this.levelSystem = levelSystem;
level = levelSystem.GetLevelNumber();
experience = levelSystem.GetExperience();
}
public void SetLevelSystemAnimation(LevelSystemAnimation levelSystemAnimation)
{ //Set the LevelSystem object
this.levelSystemAnimation = levelSystemAnimation;
//Update the starting values
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
//Subscribe to the chnaged events
levelSystemAnimation.OnExperienceChanged += LevelSystemAnimation_OnExperienceChanged;
levelSystemAnimation.OnLevelChanged += LevelSystemAnimation_OnLevelChanged;
}
private void LevelSystemAnimation_OnLevelChanged(object sender, System.EventArgs e)
{
//Level changed, update text
SetLevelNumber(levelSystemAnimation.GetLevelNumber());
FirebaseManager.instance.ActivateXPUpdate();
}
private void LevelSystemAnimation_OnExperienceChanged(object sender, System.EventArgs e)
{
//Experience changed, update bar size
SetExperienceBarSize(levelSystemAnimation.GetExperienceNormalized());
SetXpAmount(levelSystemAnimation.GetXpAmount());
FirebaseManager.instance.ActivateXPUpdate();
}
public void AddXpToAccount()
{
endGameResults.SetActive(false);
levelSystem.AddExperience(25);
}
}
There's more code but I think the problem can be solved with these. Any suggestions would help.
I have a button for showing rewarded advertisement. If the advertisement is loaded, I want to enable this button, also if the advertisement is not loaded, I want to disabled this button. But, the code is not working, When i have no internet connection, the button is always enabled. How can i do this issue?
Here is my code :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RewardedShop : MonoBehaviour
{
public static RewardedShop Instance { get; set; }
private void Awake()
{
Instance = this;
}
public string appkey;
public GameObject afterRewardedScreen, mainScreen;
public Button btnWatchSHOP;
public GameObject btnActive;
RewardedGameObject[] go;
// Start is called before the first frame update
void Start()
{
IronSource.Agent.shouldTrackNetworkState(true);
IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvaibilityChangedEvent;
IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
//IronSourceEvents.onRewardedVideoAdReadyEvent += OnRewardedVideoAdReady;
btnWatchSHOP.interactable = false;
}
public void showRewarded()
{
if (IronSource.Agent.isRewardedVideoAvailable())
{
counter = 0;
IronSource.Agent.showRewardedVideo("ShopRewarded");
}
}
void RewardedVideoAdClosedEvent()
{
IronSource.Agent.init(appkey, IronSourceAdUnits.REWARDED_VIDEO);
IronSource.Agent.shouldTrackNetworkState(true);
}
void RewardedVideoAvaibilityChangedEvent(bool available)
{
bool rewardedVideoAvailability = available;
BtnActive();
}
int counter = 0;
void RewardedVideoAdRewardedEvent(IronSourcePlacement ssp)
{
if (counter < 1)
{
RewardHandlerSHOP.Instance.Reward();
counter++;
}
}
public void Reward()
{
PlayerPrefs.SetInt("totalCoin", PlayerPrefs.GetInt("totalCoin") + 150);
GameObject.Find("TxtTotalSHOPCoin").GetComponent<Text>().text = PlayerPrefs.GetInt("totalCoin").ToString();
SoundManager.Instance.PlayEarnGoldSound();
}
public void BtnActive()
{
bool available = IronSource.Agent.isRewardedVideoAvailable();
if (available)
{
btnWatchSHOP.interactable = true;
}
else
{
btnWatchSHOP.interactable = false;
}
}
}
Hello guys I'm newbie in unity and c# i was trying make little game but i have a an error i cant fix that can you help me? and whats wrong? you explain so I can learn? I'm making a mistake somewhere but I don't understand where...
I also looked at the friends who got the same error in the forums, but I could not find the relevance of what was said with my code.I also made these codes with the things I learned on youtube, so if there are mistakes, please excuse me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
public class LobbyNetworkManager : MonoBehaviourPunCallbacks
{
int number;
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;
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);
_leaveRoomButton.interactable = true;
}
public override void OnLeftRoom()
{
_statusField.text = "Lobby";
Debug.Log("Left Room");
_leaveRoomButton.interactable = false;
}
#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 current list of room
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);
}
}
public void JoinRoom(string roomName)
{
PhotonNetwork.JoinRoom(roomName);
}
public void CreateRoom()
{
number = Random.Range(1000000, 9999999);
PhotonNetwork.CreateRoom(su.text + number, new RoomOptions() { MaxPlayers = 4 }, null);
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class RoomItemUI : MonoBehaviour
{
public LobbyNetworkManager LobbyNetworkParent;
[SerializeField] private Text _roomName;
public void SetName(string roomName)
{
_roomName.text = roomName;
}
public void OnJoinPressed()
{
LobbyNetworkParent.JoinRoom(_roomName.text);
}
}
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];
}
}
}