- Home /
How to setActive an Object form another scene? Help please.
So I have two scenes, its like a character selection, in the first scene I have UI images and buttons for the character. in the second scene I have the characters Objects but all set to inactive. I want to push a button in the scene1 to load to scene2 and in the same time activate Object in the scene2.
I've tried a lot of scripts but nothing seems to work.
My basic question is how I can Setactive an object from another scene than the scene which contains the object?
any help would be appreciated.
Answer by marcrem · Jul 17, 2017 at 10:51 PM
You should create an empty GameObject that you call something like CharacterManager, and on this object you'd have your script that keeps the information on which character was selected. Also, in the Start() method, you should add DontDestroyOnLoad(this.gameObject);
this way your CharacterManager will still be in your scene when you go to scene two, so you can access the variables in there.
Let me know if that's not clear enough.
Answer by Drewtooroo · May 18, 2018 at 01:31 AM
There are not many obvious ways to pass data between scenes in Unity. The most straightforward way I know of would be to save the character's name in a static field when the button is pressed in scene 1. When scene 2 loads, you can have a script that reads the character's name and activates the correct object. The boot up script in scene 2 might look like:
public class CharacterLoader : MonoBehaviour {
// Static fields can be accessed from anywhere, and don't belong
// to any of the class instances.
public static string selectedCharacterName;
[SerializeField] GameObject characterOne;
[SerializeField] GameObject characterTwo;
void Start () {
if (selectedCharacterName == "characterOneName") {
characterOne.SetActive(true);
} else if (selectedCharacterName == "characterTwoName") {
characterTwo.SetActive(true);
} else {
// If nothing works, load character one as a default.
// Useful for loading the scene by itself for testing.
characterOne.SetActive(true);
}
}
}
There's lots of ways to improve this. You can use an enum to stay away from strings, for example, or you could use a ScriptableObject instead of a static field to make everything more visible and lean further into Unity's inspector system.