- Home /
How can I change the character for the gameplay after selecting the character?
I have a 2D game in which my character goes left or right avoiding knives. I have 1 character set up with animations of walk and idle. I want a second character to be added, and the user to be able to choose to play with. My question is how can I change the character in the gameplay scene after the character selection which is done in another scene (before gameplay)? I have PlayerMove.cs
which includes these codes to make walk animation.
if(h > 0)
{
temp.x += speed * Time.deltaTime;
sr.flipX = false;
anim.SetBool("walk",true);
}
else if (h < 0)
{
temp.x -= speed * Time.deltaTime;
sr.flipX = true;
anim.SetBool("walk",true);
}
else if (h == 0)
{
anim.SetBool("walk",false);
}
So I should also somehow use walk or walk1 in these codes to make them have animation when they move. I was planning to active an object(Player) which is selected. But as far as I am concerned, I can not access the gameplay scene during the selectPlayer Scene because it is not loaded yet.
Answer by tormentoarmagedoom · Mar 04, 2020 at 08:49 AM
Hello.
First, you need to have the second character. It cna be a copy of the firstone. And at the start of the scene, disable the non selected one.
To know what the player selected in the last scene, you need to use the DontDestroyOnLoad property on some object (like a Game Manager) that will not be destroyed when changing scenes, so you can "save" the info.
I recommend you to watch the Persistance Data from official Unity tutorials.
Good luck!
Answer by Getsumi3 · Mar 04, 2020 at 08:57 AM
Hi.
The easiest way is to create two arrays (or List) with your charactes and save data to PlayerPrefs:
First list will contain all your characters on Selector scene.
Second list also will contain all your characters but on Gameplay screen and they're state must be set to SetActive(false).
On SelectPlayer scene when you select a character write selected characters ID to PlayerPrefs.
public List<GameObject> characters = new List<GameObject>();
public GameObject selectedCharacter;
//Assign this method to the button that should select the character
public void SelectCharacter(int ID)
{
selectedCharacter = characters[ID];
PlayerPrefs.SetInt("CharID", ID);
}
And on Gameplay scene when the scene is loaded get the data about saved character ID from PlayerPrefs, find this ID in your List and make the character with this ID visible SetActive(true). public List characters = new List(); public GameObject selectedCharacter;
private void Start()
{
selectedCharacter = characters[PlayerPrefs.GetInt("CharID")];
selectedCharacter.SetActive(true);
}
P.S: Code not tested.