I implemented character selection with the following script:
public Image image;
public Sprite[] characters;
private int currentCharacter;
private int savedCharacter;
public Button selectButton;
public GameObject characterSelectionScreen;
// Start is called before the first frame update
void Start()
{
//Check save file if player previously chose a character, otherwise set default
savedCharacter = PlayerPrefs.GetInt("playerSkin", 0);
currentCharacter = PlayerPrefs.GetInt("playerSkin", 0);
image = GetComponent<Image>();
image.sprite = characters[currentCharacter];
}
private void OnEnable()
{
//Check save file if player previously chose a character, otherwise set default
savedCharacter = PlayerPrefs.GetInt("playerSkin", 0);
currentCharacter = PlayerPrefs.GetInt("playerSkin", 0);
image = GetComponent<Image>();
image.overrideSprite = characters[currentCharacter];
}
// Update is called once per frame
void Update()
{
if (savedCharacter == currentCharacter)
{
selectButton.interactable = false;
selectButton.GetComponentInChildren<Text>().text = "Selected";
}
else
{
selectButton.interactable = true;
selectButton.GetComponentInChildren<Text>().text = "Select";
}
}
public void PreviousCharacter()
{
currentCharacter--;
if (currentCharacter < 0)
{
currentCharacter = characters.Length - 1;
}
image.overrideSprite = characters[currentCharacter];
}
public void NextCharacter()
{
currentCharacter++;
if (currentCharacter == characters.Length)
{
currentCharacter = 0;
}
image.overrideSprite = characters[currentCharacter];
}
public void SelectCharacter()
{
PlayerPrefs.SetInt("playerSkin", currentCharacter);
savedCharacter = PlayerPrefs.GetInt("playerSkin", 0);
}
The way it works is like this: a variable ‘playerSkin’ is saved in PlayerPrefs. Each number (0,1,2…) represents a specific screen and I find that the easiest way to distinguish them. On the character selection screen you cycle through characters and when you press ‘Select’, the selected character is saved in PlayerPrefs - a number that represents that character skin.
What I want to do next is somehow lock all characters so that player can unlock them later by playing the game. My first idea was to store an boolean array somewhere where each array index would represent whether that character is locked or not. For example, ‘isCharacterLocked[1] = true’ means that character nr. 1 is unlocked and can be selected.
However, arrays cannot be stored so I don’t know any other optimal way to save info about characters that are locked or not. One idea would be to have a special bool variable for each character skin saved in PlayerPrefs but I didn’t try that yet and I’m worried it would clutter up the PlayerPrefs file if I’ll have lots of characters.