first, there is a singleton object simply is subscribed to activeSceneChanged
SomeSingleton.cs
void Awake ()
{
Debug.LogError ("AWAKE");
if (instance == null) {
Debug.LogError ("instance == null");
instance = this;
MusicController.instance = this;
SceneManager.activeSceneChanged += OnSceneChanged;
DontDestroyOnLoad (this.gameObject);
} else {
Debug.LogError ("destroy");
Destroy (this.gameObject);
}
}
void OnSceneChanged (Scene previousScene, Scene changedScene)
{
Debug.LogError ("OnSceneChanged changedScene = " + changedScene.name);
}
from Lobby Scene player moves to Room Scene.
in room scene.
the "Arena" Scene gets preloaded for better game experience.
LoadSceneAsync("Arena")
with allowSceneActivation = false
when player clicks play button, sets allowSceneActivation = true
but when user decides to go back and clicks Leave Button, LoadScene("Lobby") gets called.
At this time in console, it will Log
LOGS
OnSceneChanged changedScene = Lobby // time : 0.793
OnSceneChanged changedScene = Room // time : 3.982
[when player clicks Leave Button]
OnSceneChanged changedScene = Arena // time : 7.583
OnSceneChanged changedScene = Lobby // time : 7.583
like this...
it just gets activated but wont actually load the scene. why is Arena getting activatd? how to solve this problem???
should i do some unload thing to the AsyncLoading?
==== EDITED =====
when leave button clicked
public void LeaveRoom ()
{
print ("Leave Room And Move To Lobby");
SetCanStartIfMasterClient (false);
PhotonNetwork.LeaveRoom ();
AdmobController.DestroyBanner ();
Waiting.instance.StartWaiting (waitingForLeaveRoomData);
SceneFader.instance.LoadSceneWhenFadingComplete (SceneType.Lobby);
}
in SceneFader.cs
public enum SceneFadeType
{
FadeIn = 1,
FadeOut = -1
}
public class SceneFader : MonoBehaviour
{
public static SceneFader instance;
void Awake ()
{
instance = this;
// StartFadeOut
StartFading (SceneFadeType.FadeOut, null);
}
public void LoadSceneWhenFadingComplete (SceneType sceneType)
{
// 1. start Fading
// 2. on fading complete, LoadScene
StartFading
(
fadeType: SceneFadeType.FadeIn,
onFadingComplete: () => {
SceneManager.LoadScene (sceneType.ToString ());
}
);
}
public void LoadSceneWhenFadingCompleteAsync (ScenePreloader scenePreloader)
{
// 1 start preloading scene
// 2 on preloading complete, start fading
// 3 on fading complete LoadScene
scenePreloader.AddOnPreloadCompleteAndTriggerIfLoaded (
onPreloadComplete: () => {
StartFading (
fadeType: SceneFadeType.FadeIn,
onFadingComplete: () => {
scenePreloader.ActivateSceneWhenReady ();
}
);
}
);
}
private void StartFading (SceneFadeType fadeType, Action onFadingComplete)
{
Debug.LogWarning ("StartFAding ");
ScreenFader.instance.BeginFade (fadeType, onFadingComplete);
AudioMasterController.instance.StartFading (fadeType, null);
}
}
in ScenePreloader.cs
public class ScenePreloader : MonoBehaviour
{
Action<float> onPreloadRateChanged;
Action onPreloadComplete;
public AsyncOperation sceneLoader;
public bool isPreloadCompleted;
public void StartPreloadingScene (SceneType sceneType, LoadSceneMode loadSceneMode, Action<float> onPreloadRateChanged = null, Action onPreloadComplete = null)
{
this.onPreloadComplete = onPreloadComplete;
this.onPreloadRateChanged = onPreloadRateChanged;
StartCoroutine (PreloadSceneOperation (sceneType, loadSceneMode));
}
public IEnumerator PreloadSceneOperation (SceneType sceneType, LoadSceneMode loadSceneMode = LoadSceneMode.Single)
{
print ("PreloadSceneOperation sceneType = " + sceneType.ToString ());
sceneLoader = SceneManager.LoadSceneAsync (sceneType.ToString (), loadSceneMode);
sceneLoader.allowSceneActivation = false;
while (!sceneLoader.isDone) {
yield return null;
if (sceneLoader.progress >= 0.9f) {
print ("onPreloadComplete");
isPreloadCompleted = true;
if (onPreloadComplete != null) {
onPreloadComplete ();
}
break;
} else {
if (onPreloadRateChanged != null) {
onPreloadRateChanged (sceneLoader.progress);
}
}
}
}
public void ActivateSceneWhenReady ()
{
sceneLoader.allowSceneActivation = true;
}
public void AddOnPreloadCompleteAndTriggerIfLoaded (Action onPreloadComplete)
{
AddOnPreloadComplete (onPreloadComplete);
if (isPreloadCompleted) {
print ("isAlreadyLoadedTrigeringCallback");
onPreloadComplete ();
}
}
public void AddOnPreloadComplete (Action onPreloadComplete)
{
this.onPreloadComplete += onPreloadComplete;
}
public void SetOnLoadProgressValueChanged (Action<float> onLoadProgressValueChanged)
{
this.onPreloadRateChanged = onLoadProgressValueChanged;
}
}
Related
In my project, the banner opens after the scene is reloaded, everything seems to be in order in the editor.
Everything works fine in the editor, I checked it, but it’s only worth building the project on Android, it doesn’t work there normally. It will appear only after the scene is reloaded, and then not immediately with a delay of 2-3 seconds.
My code:
using UnityEngine;
using System.Collections;
using UnityEngine.Advertisements;
public class BannerAd : MonoBehaviour
{
[SerializeField] BannerPosition _bannerPosition;
[SerializeField] private string _androidAdUnitId = "Banner_Android";
[SerializeField] private string _iOSAdUnitId = "Banner_iOS";
private string _adUnitId;
private void Awake()
{
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSAdUnitId
: _androidAdUnitId;
}
private void Start()
{
Advertisement.Banner.SetPosition(_bannerPosition);
LoadBanner();
}
private IEnumerator LoadAdBanner()
{
yield return new WaitForSeconds(1f);
LoadBanner();
}
public void LoadBanner()
{
BannerLoadOptions options = new BannerLoadOptions
{
loadCallback = OnBannerLoaded,
errorCallback = OnBannerError
};
Advertisement.Banner.Load(_adUnitId, options);
}
private void OnBannerLoaded()
{
Debug.Log("Banner loaded");
ShowBannerAd();
}
private void OnBannerError(string message)
{
Debug.Log($"Banner Error: {message}");
}
public void ShowBannerAd()
{
BannerOptions options = new BannerOptions
{
clickCallback = OnBannerClicked,
hideCallback = OnBannerHidden,
showCallback = OnBannerShown
};
Advertisement.Banner.Show(_adUnitId, options);
}
public void HideBannerAd()
{
Advertisement.Banner.Hide();
}
private void OnBannerClicked() { }
private void OnBannerShown() { }
private void OnBannerHidden() { }
}
It might be the ad is still not initialized when you call LoadBanner so it doesn't work at first. The best is to call LoadBanner when Initialization is complete. Set _testMode to true or false based on your need.
public class BannerAd : MonoBehaviour, IUnityAdsInitializationListener
{
[SerializeField] bool _testMode = true;
private string _adUnitId;
void Awake()
{
InitializeAds();
}
public void InitializeAds()
{
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSGameId
: _androidGameId;
Advertisement.Initialize(_adUnitId, _testMode, this);
}
public void OnInitializationComplete()
{
LoadBanner();
}
//rest of the code
}
}
I used the code from Unity and the rewards are multiples... first 1 then 2 then 3 and increasing... i tried deleting some code, but keep doing the same, then this happened.
I searched online and i couldn't find anything that explains clicking the rewarded ads button more than once.
Everything (apparently) is working fine only if i don't assing a button and leave the "SerializeField" empty, because if i remove the button, goes back to give more rewards... can somebody check this and tell me what's going on? i add the code Here
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.UI;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidGameId = "4634758";
[SerializeField] string _iOSGameId = "4634759";
[SerializeField] bool _testMode = false;
private string _gameId;
[SerializeField] Button _showAdButton;
[SerializeField] string rewardAndroidAdUnitId = "Rewarded_Android";
[SerializeField] string rewardiOSAdUnitId = "Rewarded_iOS";
string rewardAdUnitId = null; // This will remain null for unsupported platforms
void Awake()
{
_gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSGameId
: _androidGameId;
rewardAdUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? rewardiOSAdUnitId
: rewardAndroidAdUnitId;
Advertisement.Initialize(_gameId, _testMode, this);
rewardAdUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? rewardiOSAdUnitId
: rewardAndroidAdUnitId;
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
LoadRewardedAd();
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
#region REWARDED ADS
public void LoadRewardedAd()
{
Debug.Log("Loading Ad: " + rewardAdUnitId);
Advertisement.Load(rewardAdUnitId, this);
}
public void ShowRewardedAd()
{
Advertisement.Show(rewardAdUnitId, this);
}
#endregion
public void OnUnityAdsAdLoaded(string adUnitId)
{
if (adUnitId.Equals(rewardAdUnitId))
{
// Configure the button to call the ShowAd() method when clicked:
//_showAdButton.onClick.AddListener(ShowRewardedAd);
// Enable the button for users to click:
//_showAdButton.interactable = true;
Debug.Log("RewardedAds Loaded");
}
}
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (adUnitId.Equals(rewardAdUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
_showAdButton.onClick.RemoveAllListeners(); //with this line of code the problem is solved but shows the NullReference.
// Load another ad:
Advertisement.Load(rewardAdUnitId, this);
}
}
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
if (adUnitId.Equals(rewardAdUnitId))
{
Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
}
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
if (adUnitId.Equals(rewardAdUnitId))
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
}
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
void OnDestroy()
{
//with or without it doesn't change, it works only when the game is closed, and when reopen is working the same
//_showAdButton.onClick.RemoveAllListeners();
}
}
SOLVED!!
So, basically the script from Unity somehow has an unknown error, i couldn't explain myself how or from where... so the solution i fould was to add a bool in this case showAd = false and implemented it inside the showAd and the OnUnityAdsShowComplete functions, fortunatelly that was enough to solve the issue, now I can put the script in the button or in an AdManager and call the funtion from the button in the section OnClick() either way now is not showing neither error neither multiples with the rewards.
Hope it will be usefull for someone else.
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.UI;
public class AdsInitializer : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
{
[SerializeField] string _androidGameId = "4634758";
[SerializeField] string _iOSGameId = "4634759";
[SerializeField] bool _testMode = true;
private string _gameId;
[SerializeField] Button _showAdButton; //You can remove this if want to add the function manually from OnClick()
[SerializeField] string _androidAdUnitId = "Rewarded_Android";
[SerializeField] string _iOSAdUnitId = "Rewarded_iOS";
string _adUnitId = null; // This will remain null for unsupported platforms
private bool showAd = false;
void Awake()
{
InitializeAds();
Debug.Log("Awake");
_adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSAdUnitId
: _androidAdUnitId;
Debug.Log("the _adUnitId is: " + _adUnitId);
}
public void InitializeAds()
{
_gameId = (Application.platform == RuntimePlatform.IPhonePlayer)
? _iOSGameId
: _androidGameId;
Advertisement.Initialize(_gameId, _testMode, this);
}
public void OnInitializationComplete()
{
Debug.Log("Unity Ads initialization complete.");
LoadAd();
}
public void OnInitializationFailed(UnityAdsInitializationError error, string message)
{
Debug.Log($"Unity Ads Initialization Failed: {error.ToString()} - {message}");
}
public void LoadAd()
{
// IMPORTANT! Only load content AFTER initialization (in this example, initialization is handled on top of the script).
Debug.Log("Loading Ad: " + _adUnitId);
Advertisement.Load(_adUnitId, this);
}
// If the ad successfully loads, add a listener to the button and enable it:
public void OnUnityAdsAdLoaded(string adUnitId)
{
Debug.Log("Ad Loaded: " + adUnitId);
if (adUnitId.Equals(_adUnitId))
{
// Configure the button to call the ShowAd() method when clicked:
_showAdButton.onClick.AddListener(ShowAd); //You can remove this if want to add the function manually from OnClick()
// Enable the button for users to click:
_showAdButton.interactable = true; //You can remove this if want to add the function manually from OnClick()
}
}
// Implement a method to execute when the user clicks the button:
public void ShowAd()
{
if (showAd == false)
{
Debug.Log("Showing Ad");
// Disable the button:
_showAdButton.interactable = false; //You can remove this if want to add the function manually from OnClick()
// Then show the ad:
Advertisement.Show(_adUnitId, this);
_showAdButton.onClick.RemoveAllListeners(); //You can remove this if want to add the function manually from OnClick()
Debug.Log("All Listeners Removed");
showAd = true;
}
}
// Implement the Show Listener's OnUnityAdsShowComplete callback method to determine if the user gets a reward:
public void OnUnityAdsShowComplete(string adUnitId, UnityAdsShowCompletionState showCompletionState)
{
if (showAd == true)
{
if (adUnitId.Equals(_adUnitId) && showCompletionState.Equals(UnityAdsShowCompletionState.COMPLETED))
{
Debug.Log("Unity Ads Rewarded Ad Completed");
// Grant a reward.
// Load another ad:
Advertisement.Load(_adUnitId, this);
showAd = false;
}
}
}
public void OnUnityAdsFailedToLoad(string adUnitId, UnityAdsLoadError error, string message)
{
Debug.Log($"Error loading Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowFailure(string adUnitId, UnityAdsShowError error, string message)
{
Debug.Log($"Error showing Ad Unit {adUnitId}: {error.ToString()} - {message}");
// Use the error details to determine whether to try to load another ad.
}
public void OnUnityAdsShowStart(string adUnitId) { }
public void OnUnityAdsShowClick(string adUnitId) { }
}
added a leaderboard to the Google Play Service. Resources are added, authorization is working, adding a record is working. But when use ShowLeaderboardUI() only shows the name of the highscore table, but there are no highscores. Help pls ;(
CODE Ads Init:
public class AdsInitialize : MonoBehaviour
{
public static AdsInitialize instance = null;
private string LEADER_BOARD = "******";
public Text _text;
private void Awake()
{
if (instance == null)
{
instance = this;
MobileAds.Initialize(initStatus => { });
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
Social.localUser.Authenticate(success =>
{
if (success)
{
_text.text = "Auth working";
}
else
{
_text.text = "Auth not working";
}
});
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
public void ShowLeaderBoard()
{
//Social.ShowLeaderboardUI();
PlayGamesPlatform.Instance.ShowLeaderboardUI(LEADER_BOARD);
}
}
Write highscores:
Social.ReportScore(_time, AdsInitialize.instance.LEADER_BOARD, (bool success) => {
if (success)
{
_text.text = "ReportScore working";
}
else
{
_text.text = "ReportScore not working";
}
});
Show leaderboard in menu (this method is hanging on button):
public void ShowLeaderBoard()
{
AdsInitialize.instance.ShowLeaderBoard();
}
You need update your Google Play Games at phone
i am trying to make a lives counter in unity with c# so i made a ui text in unity with the value Livesvalue = 3; in a other script i have the deatchscene so when i die the value goes to the other script en does -1 but i get an eroor that the value does not exist
UItext code:
public class livesscript : MonoBehaviour
{
public static int Livesvalue = 3;
Text Lives;
// Start is called before the first frame update
void Start()
{
Lives = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
Lives.text = "Lives: " + Livesvalue;
}
}
deathscene code:
private void StartDeathSequence()
{
state = State.Dead;
audioSource.Stop();
audioSource.PlayOneShot(death);
deathpart.Play();
mainEnginepart.Stop();
livesscript.Livesvalue -= 1;
Invoke("RespawnLevel", Waitdead); // parameterise time
LivesRespawn();
}
private void LivesRespawn()
{
if (Livesvalue == 0)
{
SceneManager.LoadScene(0);
}
}
When referencing a static variable you need to include the class name and a period before the variable.
private void LivesRespawn()
{
if (Livesvalue == 0)
{
SceneManager.LoadScene(0);
}
}
change to
private void LivesRespawn()
{
if (livesscript.Livesvalue < 1)
{
SceneManager.LoadScene(0);
}
}
So, I am working on a Unity project in which I need to implement client/server functionality.
The client has its own "scene" and the server has its own scene as well. The server code and a networkView are attached to the Main Camera in their scene. The code is as follows:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Collections.Generic;
public class NetworkManagerCS : MonoBehaviour {
public int loadlevel;
public int connectPort = 25000;
public string hostname;
public string GameName = "Historical Grounds";
private bool refreshing;
private HostData[] hostData;
private Dictionary<string, string> playerList = new Dictionary<string, string>();
string textToEdit = "Type text here";
// This is for debuggin purposes only!! Will be deprecated
public void OnGUI() {
if (Network.peerType == NetworkPeerType.Disconnected) {
GUILayout.Label("Connection status: Disconnected");
GUILayout.BeginVertical();
if (GUILayout.Button("Connect as client"))
{
ConnectToServer();
}
if (GUILayout.Button("Start Server"))
{
Network.InitializeServer(4, connectPort, true);
MasterServer.RegisterHost(GameName, "Tutorial Game", "This is a turn based shooter");
//Network.Instantiate(camera, transform.position, transform.rotation, 0);
}
GUILayout.EndVertical();
}
else
{
// Connecting...
if (Network.peerType == NetworkPeerType.Connecting)
{
GUILayout.Label("Connection status: Connecting");
}
// Clientside buttons
else if (Network.peerType == NetworkPeerType.Client)
{
GUILayout.Label("Connection status: Client!");
GUILayout.Label("Ping to server: " + Network.GetAveragePing(Network.connections[0]));
textToEdit = GUILayout.TextField(textToEdit, 25);
if( GUILayout.Button("Attack Server")) {
float[] args = new float[3];
args[0] = float.Parse(textToEdit);
args[1] = 4.123f;
args[2] = 23.2f;
networkView.RPC("AttackServer", RPCMode.AllBuffered, args);
}
}
// Serverside
else if (Network.peerType == NetworkPeerType.Server)
{
GUILayout.Label("Connection status: Server!");
GUILayout.Label("Hostname is:" + System.Net.Dns.GetHostName() );
GUILayout.Label("Connections: " + Network.connections.Length);
}
// Disconnect happens in both server and client
if (GUILayout.Button("Disconnect"))
{
Network.Disconnect(200);
}
}
}
// AKA While(true)
public void Update() {
/*
* If we have a "refreshing" flag, then we poll the master server
* until we get a length larger than 0. Then, we connect to server.
*/
if(refreshing) {
if (MasterServer.PollHostList().Length > 0) {
refreshing = false;
Debug.Log(MasterServer.PollHostList().Length);
hostData = MasterServer.PollHostList();
ConnectToServer();
}
}
}
/*
* If hostData does not exist, refresh
* Otherwise, connect to the first game you see.
*
* This is the "dumb" approach, but I assume that there are not going to be more
* than one game running at a time...
*/
public void ConnectToServer() {
if (hostData == null) {
MasterServer.RequestHostList(GameName);
refreshing = true;
} else {
Network.Connect(hostData[0]);
}
}
/*
* Keeping this here so that I will remember to add system info sends
*/
public void OnConnectedToServer()
{
//Application.LoadLevel(loadlevel);
}
/*
* DEBUG FUNCTION!!! This will be called when someone disconnected from
* the msater server
*/
public void OnDisconnectedFromServer(NetworkDisconnection info) {
if (info == NetworkDisconnection.LostConnection) {
if (Network.peerType == NetworkPeerType.Client) {
Debug.Log ("Client has lost connection");
} else {
Debug.Log ("Server has lost connection");
}
} else {
Debug.Log ("Disconnected Successfully");
}
}
/*
* Lawl, fail....
*/
public void OnFailedToConnect(NetworkConnectionError error)
{
Debug.LogError(error.ToString());
Network.Disconnect(400);
}
/*
* The purpose of this function is to assign a monster to a player
* Once all monsters have been assigned, I guess the Update() function will
* RPC to the phones that they are ready to play.
*/
public void OnPlayerConnected(NetworkPlayer player) {
networkView.RPC("assignPlayer", RPCMode.All, player);
}
/*
* Not interesting... Server initialized..
*/
public void OnServerInitialized()
{
//Application.LoadLevel(loadlevel);
Debug.Log("Server Started");
}
void OnMasterServerEvent(MasterServerEvent msg) {
if (msg == MasterServerEvent.RegistrationSucceeded){
Debug.Log("Registered Server!");
Network.isMessageQueueRunning = true;
}
}
/*void OnPlayerDisconnected(NetworkPlayer player) {
Transform playerTransform = GameObject.Find("Player_" + player.guid);
if (playerTransform != null) {
Destroy (playerTransform.gameObject);
}
Network.RemoveRPCs(player);
Network.DestroyPlayerObjects(player);
}*/
// Testers - Should deprecate
/*[RPC]
public void AttackServer(float[] args) {
foreach (float value in args) {
Debug.Log ("Server is under attack with force " + value);
}
}*/
// RPC's Server Side
[RPC]
public void sendLifeCount(NetworkPlayer player) {
Debug.Log("Sending Life Count to " + player.ipAddress);
}
[RPC]
public void isDead(NetworkPlayer player) {
Debug.Log("You're dead! " + player.ipAddress);
}
[RPC]
public void unlockScreen(NetworkPlayer player) {
Debug.Log("Unlocking screen for.." + player.ipAddress);
}
[RPC]
public void assignPlayer(NetworkPlayer player) {
playerList.Add(player.guid, "1");
Debug.Log(playerList[player.guid]);
Debug.Log("Player connected from: " + player.ipAddress + ":" + player.port);
Debug.Log("The player on IP " + player.ipAddress + " has been assigned the x monster");
}
public Object networkprefab { get; set; }
}
The client on the other hand, is in another scene and its code is here: (no networkView attached, due to problems...
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text.RegularExpressions;
public center code herelass InputField : MonoBehaviour {
// Client-server bullshit
private int loadlevel;
private HostData[] hostData;
private bool refreshing;
public string GameName = "Historical Grounds";
private bool connected;
public Canvas mainCanvas;
public Canvas gameCanvas;
public Button Connect;
public Text nameFieldInput;
public Text nameField;
public Text Error;
private string userName;
void Awake()
{
if (connected)
{
mainCanvas.enabled = false;
gameCanvas.enabled = true;
}
else {
mainCanvas.enabled = true;
gameCanvas.enabled = false;
}
Debug.Log(connected);
}
public void Update()
{
/*
* If we have a "refreshing" flag, then we poll the master server
* until we get a length larger than 0. Then, we connect to server.
*/
if (refreshing)
{
if (MasterServer.PollHostList().Length > 0)
{
refreshing = false;
Debug.Log(MasterServer.PollHostList().Length);
hostData = MasterServer.PollHostList();
ConnectToServer();
}
}
}
public void onConnect()
{
ConnectToServer();
}
public void OnConnectedToServer()
{
var viewID = Network.AllocateViewID();
}
public void ConnectToServer()
{
if (hostData == null)
{
MasterServer.RequestHostList(GameName);
refreshing = true;
}
else
{
if (Switch())
{
connected = true;
Network.Connect(hostData[0]);
}
}
}
private bool Switch(){
userName = nameFieldInput.text;
Debug.Log(userName);
if(Validate(userName)){
nameField.text = userName;
mainCanvas.enabled = false;
gameCanvas.enabled = true;
connected = true;
return true;
} else {
Error.text = "Invalid name!" + "\n" + "Name should be 2-8 characters and start with a capital letter";
return false;
}
}
private bool Validate(string input){
string pattern = #"^[A-Z][A-Za-z0-9][A-Za-z0-9]+";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
return true;
}
return false;
}
public void OnDisconnectedFromServer(NetworkDisconnection info)
{
if (info == NetworkDisconnection.LostConnection)
{
if (Network.peerType == NetworkPeerType.Client)
{
Debug.Log("Client has lost connection");
}
else
{
Debug.Log("Server has lost connection");
}
}
else
{
Debug.Log("Disconnected Successfully");
}
}
public void OnFailedToConnect(NetworkConnectionError error)
{
Debug.LogError(error.ToString());
Debug.Log("FAIL!");
}
public void OnDisconnectedFromServer()
{
connected = false;
Debug.Log("Lawl Disconnected");
}
}
TL;DR: I keep getting that error message when trying to invoke an RPC ( fire() ) from the client to the server. Anyone know why?
Thanks!!