Find reference in difference scene unity - c#

I'm confused about finding reference GameObject but different Scene and set the onclick when difference scene, so I have GameManager who manage all but available only on the Main menu. So I decide to make Dontdestroyonload, the issue start at this, so when I play to the MainGame Scene, the field of GameManager at inspector will find, but I can't drag n drop different scene, right? That confuses me.
And if the GameManager at the MainMenu scene, the question is how to drag n drop at the onClick event, like I want pause button active or something else in the game.
]3
I tried with onLloadscene(scene s, Mode mode), but nothing happens, and here the scrip for the GameManager. :
public static GameManager gameManager;
[Header("Main Menu panels")]
public GameObject startPanel;
public GameObject settingPanel;
public GameObject levelPanel;
[Header("InGame Panels")]
#region Panel
public GameObject pausePanel;
public GameObject ObjectivePanel;
public GameObject shopPanel;
private int click = 0;
[Header("Int Tweaks")]
public int indexLevel;
public int onlevel;
public bool isPaused;
_levelSelect LevelSelect;
public static GameManager Instance { set; get; }
public int levelindexPlayerPrefs;
private void Awake()
{
if (gameManager != null)
{
Instance = this;
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
LevelSelect = FindObjectOfType<_levelSelect>();
OnStart();
onlevel = int.Parse(LevelSelect.levelIndex) + 1;
indexLevel = int.Parse(LevelSelect.levelIndex);
getPlayerData();
}
// Update is called once per frame
void Update()
{
ExitApp();
}
public void OnStart()
{
startPanel.SetActive(true);
settingPanel.SetActive(false);
levelPanel.SetActive(false);
}
#region Buttons
public void startbutton()
{
levelPanel.SetActive(true);
startPanel.SetActive(false);
settingPanel.SetActive(false);
}
public void backButtonMainMenu()
{
levelPanel.SetActive(false);
startPanel.SetActive(true);
settingPanel.SetActive(false);
}
public void settingbutton()
{
levelPanel.SetActive(false);
startPanel.SetActive(false);
settingPanel.SetActive(true);
}
public void PauseButton()
{
Time.timeScale = 0f;
pausePanel.SetActive(true);
ObjectivePanel.SetActive(false);
}
public void Resume()
{
Time.timeScale = 1f;
}
#endregion
public void ExitApp()
{
if (Input.GetKey(KeyCode.Escape))
{
click++;
StartCoroutine(ClickTime());
if (click>1)
{
print("Exit Game");
Application.Quit();
}
}
}
IEnumerator ClickTime()
{
yield return new WaitForSeconds(0.5f);
click = 0;
}
public void getPlayerData()
{
levelindexPlayerPrefs = PlayerPrefs.GetInt("LevelIndex", 0);
}
public void updateLevel(int Index)
{
if (levelindexPlayerPrefs < Index)
{
PlayerPrefs.SetInt("LevelIndex", Index);
levelindexPlayerPrefs = PlayerPrefs.GetInt("LevelIndex");
}
}
#region onloadedScenePickRefferences
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
pausePanel = GameObject.FindGameObjectWithTag("PausePanel");
ObjectivePanel = GameObject.FindGameObjectWithTag("ObjectivePanel");
}
#endregion
//public IEnumerator EndChapter()
//{
// updateLevel(indexLevel + 1);
// getPlayerData();
//}

Here is what I would probably do:
Have a static class for storing and sharing all your references. It doesn't have to be in any scene but simply "lives" in the assets:
public static class GlobalReferences
{
// as example just for one reference but you can implement the rest equally yourself
// here this class actually stores the reference
private static GameObject startPanel;
// A public property in order to add some logic
// other classes will always access and set the value through this property
public static GameObject StartPanel
{
get
{
// if the reference exists return it right away
if(startPanel) return startPanel;
// as a fallback try to find it
startPanel = GameObject.FindGameObjectWithTag("StartPanel");
// ofcourse it might still fail when you simply try to access it
// in a moment it doesn't exist yet
return startPanel;
}
set
{
startPanel = value;
// invoke an event to tell all listeners that the startPanel
// was just assigned
OnStartPanelReady?.Invoke();
}
}
// An event you will invoke after assigning a value making sure that
// other scripts only access this value after it has been set
// you can even directly pass the reference in
public static event Action<GameObject> OnStartPanelReady;
}
So now in your component(s) that is(are) in the new loaded scene you assign the value as early as possible (Awake). Here you can already store it via the Inspector since it is a scene reference:
public class ExampleSetter : MonoBehaviour
{
// already reference it via the Inspector
[SerializeField] private GameObject startPanel;
private void Awake()
{
// as a fallback
if(!startPanel) startPanel = GameObject.FindObjectWithTag("startPanel");
// assign it to the global class
GlobalReferences.StartPanel = startPanel;
}
}
And in other scenes that where already loaded before you add a listener so they do their stuff as soon as the other scene is ready:
public class ExampleConsumer : MonoBehaviour
{
[Header("Debug")]
[SerializeField] private GameObject startPanel;
private void Awake()
{
// Try to get the reference
startPanel = GlobalReferences.StartPanel;
// if this failed then wait until it is ready
if(!startPanel)
{
// it is save to remove callbacks even if not added yet
// makes sure a listener is always only added once
GlobalReferences.OnStartPanelReady -= OnStartPanelReady;
GlobalReferences.OnStartPanelReady += OnStartPanelReady;
}
// otherwise already do what you want
else
{
OnStartPanelReady(startPanel);
}
}
private void OnDestroy()
{
// always make sure to clean up callbacks when not needed anymore!
GlobalReferences.OnStartPanelReady -= OnStartPanelReady;
}
private void OnStartPanelReady(GameObject newStartPanel)
{
startPanel = newStartPanel;
// always make sure to clean up callbacks when not needed anymore!
GlobalReferences.OnStartPanelReady -= OnStartPanelReady;
// NOTE: It is possible that at this point it is null anyway if another
// class has set this actively to null ;)
if(startPanel)
{
// Now do something with the startPanel
}
}
}
The other way round when you need a reference in the new loaded Scene form the main scene ... it should already be set since the mainscene was loaded first and has already assigned its according references.
Now you can either go for this static class or simply implement the same logic for each reference that needs to be shared directly in an according component where you reference them via drag&drop .. it makes no difference since anyway you will use static fields and events that are not bound to any instance but the type(s) itself.

Related

Text in Canvas is not being updated correctly - Null Error

I am building out a Zelda game and I have ran into an issue -
public void UpdateCoins()
{
Debug.Log(GameManager.instance.currCoins);
//coinsText.text = "Coins " + GameManager.instance.currCoins;
}
That works as expected -
But when I do this...
public void UpdateCoins()
{
Debug.Log(GameManager.instance.currCoins);
coinsText.text = "Coins " + GameManager.instance.currCoins;
}
I receive an Object Reference not set to an instance of the object error.
As you can see it is set. Here is my simple GameManager script
public static GameManager instance;
public int currCoins;
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void GetCoins(int coinsToAdd)
{
currCoins += coinsToAdd;
UIManager.instance.UpdateCoins();
}
}
Any thoughts on why this isn't working the way it should?
Thanks!
Try add more logs
Either the coinsText or the coinsText.text is null, so what I would do is:
Debug.Log(coinsText);
if(coinsText != null) Debug.Log(coinsText.text);
I'm sure you'll make a great Zelda game but let's fix your issue here first , you are trying to access to an int GameManager.instance.currCoins
but returns null simply because the currCoins you're using is not even to been set to zero.
Also as a tip if you are going to use an int in a string text or something always use ToString() :
coinsText.text = "Coins " + GameManager.instance.currCoins.ToString();
Number 2 issue here , your use of singleton it should be like this
public static GameManager instance;
public void Awake()
{
if(instance == null){
instace = this;
}else
{
DontDestroyOnLoad(gameObject);
}
}
Last issue that may not be one now but in the future change the name of this method now while you still can public void GetCoins(int coinsToAdd)to something like AddCoins(int coinsToAdd)

Unity AudioManager PlayerPrefs Slider

I have the below audiomanager for my project. Whenever I run a game from the "Play" button in Unity - I can change the volume via slider and the settings are being saved and they load when I exit and play again via Unity's "Play" button.
However can you please explain to me why I cannot do this when I go to the PlayGame and then I go back to the main menu via "restart" button in my game? When I do that - the slider is 100% charged and it doesn't save/load new setings.
Any comments / feedback is much appreciated!
public static AudioManager AMInstance;
[SerializeField] Slider volumeSlider;
private void Awake()
{
if (AMInstance != null && AMInstance != this)
{
Destroy(this.gameObject);
return;
}
AMInstance = this;
DontDestroyOnLoad(this);
}
private void Start()
{
if (!PlayerPrefs.HasKey("musicVolume"))
{
PlayerPrefs.SetFloat("musicVolume", 1);
Load();
}
else
{
Load();
}
}
public void ChangeVolume()
{
AudioListener.volume = volumeSlider.value;
Save();
}
public void Save()
{
PlayerPrefs.SetFloat("musicVolume", volumeSlider.value);
}
public void Load()
{
volumeSlider.value = PlayerPrefs.GetFloat("musicVolume");
}
}
You will need to call PlayerPrefs.Save() before you navigate to another scene. It does get called by default OnApplicationQuit, but since you are just setting a the float, you might need to explicitly call the Save function.
Unity's documentation for PlayerPrefs.Save

Why does my non-static GameObject lose its reference in a script after scene reloaded?

I have an empty GameObject on my Canvas used to display an ad menu, which I have attached to a separate script (not on the menu itself) in a public variable through the inspector.
I am setting it inactive in a script using adMenu.SetActive(false), which works on the first playthrough of my game. However, when I restart the scene through a button in my scene, the menu loses its reference to the same GameObject in the inspector, and I receive this error:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
This has never happened to me with other GameObjects initialized in similar ways after a scene reload.
 
Additional details:
GameObject.Find() can retrieve the GameObject using its name from within the same script
DontDestroyOnLoad() is not used anywhere on the script or on the GameObject it's attached to
 
Code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
using MEC;
public class AdManager : MonoBehaviour, IUnityAdsListener
{
internal static AdManager instance;
private static bool isInitialized = false;
public GameObject adMenu;
private string placement = "rewardedVideo";
void Start()
{
instance = this;
if (!isInitialized)
{
isInitialized = true;
Advertisement.AddListener(this);
Advertisement.Initialize(Constants.appleGameId, true);
}
}
IEnumerator<float> ShowAd()
{
if (!Advertisement.IsReady())
{
yield return Timing.WaitForOneFrame;
}
Advertisement.Show(placement);
}
public void CloseAdMenu()
{
Debug.Log("Is adMenu null: " + (adMenu == null)); // Returns false on first playthrough only
adMenu.SetActive(false);
}
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
if (showResult == ShowResult.Finished)
{
CloseAdMenu();
}
}
public void OnUnityAdsReady(string placementId)
{
// throw new System.NotImplementedException();
}
public void OnUnityAdsDidError(string message)
{
// throw new System.NotImplementedException();
}
public void OnUnityAdsDidStart(string placementId)
{
// throw new System.NotImplementedException();
}
}
What happens has nothing to do with your menu object nor the static Instance.
The issue is the callback of
public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
since you registered the instance via
Advertisement.AddListener(this);
but this instance will be Destroyer after the scene was changed.
As shown in the examples you should do
private void OnDestroy()
{
Advertisement.RemoveListener(this);
}
On your restart method, you should re-activate the button with adMenu.SetActive(true), if not, when you call the scene again, adMenu GameObject is disabled, so you can't access the GameObject.
Maybe you can add a method in your AdManager like:
public void OpenAdMenu()
{
adMenu.SetActive(true);
}
and call it on AdManager.Start()

Detect changes in the value of other objects referenced in unity?

I'm trying to implement a feature that detects a change in the value of another field object reference.
For example, there is an A object, and the B object contains A.
The A object is notified by OnValidate when the field of the A object has changed.
At this time. Is there any way that "B" can detect the change of "A"?
This feature is only required in the Editor and does not include code in Runtime.
public class A : ScriptableObject
{
[SerializeField]
public string team;
private void OnValidate()
{
Debug.Log($"My team name has been changed to {team}.");
}
}
public class B : ScriptableObject
{
[SerializeField]
public A a;
private void OnValidate()
{
Debug.Log($"A changed.");
}
// How can I detect changes to A and call this functions?
private void OnATeamChanged()
{
Debug.Log($"A's team name has been changed to {a.team}.");
}
private void OnADestroyed()
{
Debug.Log($"A is missing.");
}
}
I would also propose to use events but be careful how and when you register and remove listeners!
public class A : ScriptableObject
{
// You don't need [SerializeField]
// public properties are serialized anyway
public string team;
public event Action onChanged;
public event Action onReset;
public event Action onDestroyed;
private void OnValidate()
{
Debug.Log($"My team name has been changed to {team}.");
if(onChanged == null) return;
onChanged.Invoke();
}
// This is called on reset
// But if you override this you have to set
// The default values yourself!
private void Reset()
{
team = "";
if (onReset == null) return;
onReset.Invoke();
}
// Called when object is destroyed
private void OnDestroyed()
{
if(onDestroyed == null) return;
onDestroyed.Invoke();
}
}
But now in B I would not add the listener on Awake since this adds it after every recompile and multiple times! Instead don't forget to "clean up" all listeners you ever add to avoid getting NullReferenceExceptions:
public class B : ScriptableObject
{
// You don't need [SerializeField] since public properties
// are serialized anyway
public A a;
// Internal for removing listeners later
private A lastA;
private void OnValidate()
{
// Apparently something else was changed
if(a == lastA) return;
Debug.Log("reference a changed");
// Unregister listeners for old A reference
if(lastA)
{
lastA.onChanged -= OnAChanged;
lastA.onReset -= OnAReset;
lastA.onDestroyed -= OnADestroyed;
}
// Register listeners for new A reference
// Note that it is allways possible to remove listeners first
// even if they are not there yet
// that makes sure you listen only once and don't add multiple calls
if(a)
{
a.onChanged -= OnAChanged;
a.onReset -= OnAReset;
a.onDestroyed -= OnADestroyed;
a.onChanged += OnAChanged;
a.onReset += OnAReset;
a.onDestroyed += OnADestroyed;
}
lastA = a;
}
// Make allways sure you also remove all listeners on destroy to not get Null reference exceptions
// Note that it is allways possible to remove listeners even if they are not there yet
private void OnDestroy()
{
if(!a) return;
a.onChanged -= OnAChanged;
a.onReset -= OnAReset;
a.onDestroyed -= OnADestroyed;
}
private void OnAChanged()
{
Debug.Log("A was changed");
}
private void OnAReset()
{
Debug.Log("A was reset");
}
private void OnADestroyed()
{
Debug.Log("a was destroyed");
}
}
Small optional change if you want
If you want additionally to be able to register other listeners in the Inspector the same way you do for Buttons you could simply exchange the
public event Action xy;
with
public UnityEvent xy;
and remove the if(xy == null) checks.
You would than also replace
a.onChanged -= OnAChanged;
a.onChanged += OnAChanged;
by
a.onChanged.RemoveListener(OnAChanged);
a.onChanged.AddListener(OnAChanged);
You could try to add an event
public class A : ScriptableObject
{
[SerializeField]
public string team;
public Action RaiseChangeName;
private void OnValidate()
{
Debug.Log($"My team name has been changed to {team}.");
if(RaiseChangeName != null) { RaiseChangeName(); }
}
}
public class B : ScriptableObject
{
[SerializeField]
public A a;
void Awake()
{
a.RaiseChangeName += OnATeamChanged;
}
// How can I detect changes to A and call this functions?
private void OnATeamChanged()
{
Debug.Log($"A's team name has been changed to {a.team}.");
}
}

Create events that fires off a coroutine from another script

I'm making an event that does the failLevel stuff when it fires off. For that I have made a delegate
public delegate Coroutine FailGame(IEnumerator function);
public static event FailGame gameFailedEvent;
like so and I subscribed the appropriate function to it
void Start ()
{
gameFailedEvent += StartCoroutine;
}
It works when it is called from the same script like so:
gameFailedEvent(WaitThenFailLevel());
when this WaitThenFailLevel() looks like this:
IEnumerator WaitThenFailLevel()
{
CharacterController2D.playerDied = true;
if (CharacterController2D.animState != CharacterController2D.CharAnimStates.fall)
{
CharacterController2D.currentImageIndex = 0;
CharacterController2D.animState = CharacterController2D.CharAnimStates.fall;
}
CharacterController2D.movementDisabled = true;
yield return new WaitForSeconds(0.2f);
StartCoroutine(ScaleTime(1.0f, 0.0f, 1.2f));
}
It works fine here. Now, I have another object that can kill the player (dangerous times I know) and I don't want to copy paste everything again, I just want it to fire off the static event made in the script above.
I DID try making the WaitThenFailGame function
public static
and make static all my other ienumerators but I got an error named "An object reference is required for non-static field..."
Hence I tried the event stuff.
All well and fine, but I can't call the event from the other script because I can't pass it the function from the script mentioned.
What to do now?
Here is the example code:
EventContainor.cs
public class EventContainer : MonoBehaviour
{
public static event Action<string> OnGameFailedEvent;
void Update()
{
if (Input.GetKey(KeyCode.R))
{
// fire the game failed event when user press R.
if(OnGameFailedEvent = null)
OnGameFailedEvent("some value");
}
}
}
Listener.cs
public class Listener : MonoBehaviour
{
void Awake()
{
EventContainer.OnGameFailedEvent += EventContainer_OnGameFailedEvent;
}
void EventContainer_OnGameFailedEvent (string value)
{
StartCoroutine(MyCoroutine(value));
}
IEnumerator MyCoroutine(string someParam)
{
yield return new WaitForSeconds(5);
Debug.Log(someParam);
}
}
using UnityEngine;
public class ScriptA : MonoBehaviour
{
public ScriptB anyName;
void Update()
{
anyName.DoSomething();
}
}
using UnityEngine;
public class ScriptB : MonoBehaviour
{
public void DoSomething()
{
Debug.Log("Hi there");
}
}
This is linking functions between scripts , Copied from Here, maybe coroutines are the same, Then you need to start the coroutine in void Start() {} , You may find this useful as well.

Categories

Resources