I have a question. I have a button that Loads another scene with SceneManager.LoadScene();
However, upon loading this scene I want to activate a GameObject (it’s a shop UI).
How can I do this in the same method/function?
My current method is as follows…
public void ShopMenuButton()
{
SceneManager.LoadScene(0);
GameObject shopMenu = GameObject.FindWithTag("ShopMenu");
shopMenu.gameObject.SetActive(true);
}
The error I receive is…
NullReferenceException: Object reference not set to an instance of an object
GameManager.ShopMenuButton () (at Assets/Scripts/GameManager.cs:122)
Apparently I am unsure how to assign an object from a different scene as well.
GameObject.FindWithTag
Returns one active GameObject tagged tag.
Looks like your object is not active, so FindWithTag will not find it.
So I found something that works for my particular problem on StackOverFlow. Original link here https://stackoverflow.com/questions/45107503/determine-action-according-to-previous-scene-in-unity
Basically you can resolve this by using the built in Unity class PlayerPrefs. I resolved it by having a script in the previous scene with a method that looks like this…
public void ShopMenuButton() { string goToShop = "GoShop"; SceneManager.LoadScene(0); PlayerPrefs.SetString("GoShop", goToShop); PlayerPrefs.Save(); }
^ This method sets a Key and a Value with PlayerPrefs.SetSTring() and then saves the Key/Value with PlayerPrefs.Save(). Now when you go into the next scene this preference is still saved and can be retrieved in the next script in the Awake() method like this …
private void Awake()
{
//Gets String from PlayerPref. Null by default.
string goToShop = PlayerPrefs.GetString("GoShop", null);
if (goToShop != null) //if not null then continue
{
if (goToShop == "GoShop") //if string variable == string value from PlayerPrefs
{
Debug.Log("Going to Shop!");
shopMenu.SetActive(true);
}
else
{
Debug.Log("PlayerPref String Not Assigned/Saved");
}
}
}
Also the variable shopMenu is simply an inactive GameObject that is assigned in the Unity editor just for clarification.