- Home /
Question by
yusufalp727 · Aug 24, 2021 at 09:56 AM ·
characterplayerprefssaveloadselection
Saving character selection
How can I save my character selection? I write these lines but when I reopen the game or reload the scene I lost my selection and selectedCharacter equals 0. For example if I choose second character, selectedCharacter should equal the second character value and when I reload the scene selectedCharacter should equal the second character value. I will be so happy if you help me.
using UnityEngine;
using UnityEngine.SceneManagement;
public class Characters : MonoBehaviour
{
public GameObject[] characters;
public int selectedCharacter=0;
void Start() {
while(0 < PlayerPrefs.GetInt("selectedCharacter"))
NextCharacter();
}
public void NextCharacter()
{
characters[selectedCharacter].SetActive(false);
selectedCharacter = (selectedCharacter + 1) % characters.Length;
characters[selectedCharacter].SetActive(true);
PlayerPrefs.SetInt("selectedCharacter", selectedCharacter);
}
public void PreviousCharacter()
{
characters[selectedCharacter].SetActive(false);
selectedCharacter--;
if (selectedCharacter < 0)
{
selectedCharacter += characters.Length;
}
characters[selectedCharacter].SetActive(true);
PlayerPrefs.SetInt("selectedCharacter", selectedCharacter);
}
public void StartGame()
{
PlayerPrefs.SetInt("selectedCharacter", selectedCharacter);
SceneManager.LoadScene(1,LoadSceneMode.Single);
}
}
a.png
(24.8 kB)
Comment
Best Answer
Answer by yusufalp727 · Aug 24, 2021 at 01:27 PM
Add Start() methot these lines
void Start()
{
selectedCharacter=PlayerPrefs.GetInt("selectedCharacter");
characters=new GameObject[transform.childCount];
for (int i = 0; i < characters.Length; i++)
{
characters[i]=transform.GetChild(i).gameObject;
}
foreach (GameObject go in characters)
{
go.SetActive(false);
}
if (characters[selectedCharacter])
{
characters[selectedCharacter].SetActive(true);
}
}
Your answer
Follow this Question
Related Questions
PlayerPrefs for FPS? 1 Answer
Set int to object from list? 0 Answers
Saving boolean values using PlayerPrefs 1 Answer
Save/Load Variable with playerprefs 1 Answer
How do I save and load the state of the GameObjects with PlayerPrefs? 0 Answers