问题
first of all, I'm a beginner so go easy on me. I'm trying to activate and deactivate GameObjects (players in the game) from another scene. Basically, I'm trying to change the player in the game scene by deactivate the current player model and activate the wanted player model in the game scene when the user press certain button in the shop scene, but i cant access the GameObjects (players in game scene) in the game scene from the shop scene. Does anyone know what can I do?
回答1:
You will have to save the choice in a persistent way.
Multiple options are possible. The easiest one is PlayerPrefs in your case.
Supposing you have a script you use to select your gameobject in the shop scene and a script to enable the appropriate player in the game scene.
// Shop Scene
public void SelectPlayer( GameObject gameobject )
{
PlayerPrefs.SetString( "selectedPlayer", gameObject.name ) ;
PlayerPrefs.Save();
}
// ----------
// GameScene
public GameObject[] Players; // Drag & Drop the possible players
private void Awake()
{
string selectedPlayer = PlayerPrefs.GetString( "selectedPlayer" ) ;
for( int i = 0 ; i < Players.Length ; ++i )
Players[i].SetActive( String.Equals(Players[i].name, selectedPlayer, StringComparison.Ordinal);
}
This is very simple example, you will have to adapt to fit your needs. But without your code, I can't help you more.
回答2:
You can try using PlayerPrefs. At least I tried and it worked.
First, you should create an empty GameObject in the Hierarchy as player. Then make all of your player models child of that GameObject and disable all of them.
In your shop scene add a script to change the certain PlayerPrefs when that button is clicked.
This is how PlayerPrefs are initialized (1 is the value set you can use 2 for second model and so on.);
PlayerPrefs.SetFloat("Character", 1);
And this is how they are called (The 0 here is the default value, always put 0 when you are getting a PlayerPref, it controls if you set it or not. If you don't, it simply sets it to 0.);
GameObject character = PlayerPrefs.GetFloat("Character", 0);
Then you can use an if or switch statement in the Start function of your script to enable specific player model. You can use integer or string as well.
I used an array to store my models and enable them because they are children of the player GameObject, but you can try another way if you want to.
Finally this is how I used the array thing that I said;
public GameObject[] Characters;
private GameObject subCharacter;
...
...
GameObject character = PlayerPrefs.GetFloat("Character", 0);
switch (character)
{
case 1:
subCharacter = Characters[0];
subCharacter.SetActive(true);
break;
...
...
Just put all your models into the array in the inspector window and it should work without any issues. Also, you should add the if or switch statement in the Start function of your script.
来源:https://stackoverflow.com/questions/45283407/unity-how-to-get-gameobjects-from-a-different-scene