Search code examples
unity-game-enginegameobject

Unity GameObject SetActive save to playerprefs


I want to save the active state of each individual gameobject so when you reload, the ones you collected won't be there anymore. My code :

public class PlayerController : MonoBehaviour {

     public LevelManager levelManager;          
     public GameObject[] stardust; //array of stardust in level
     public int isActive; //variable for amount of stardust collected

     void Start()
     {            
         isActive = PlayerPrefs.GetInt("stardust");
         active();
     }

     void OnTriggerEnter(Collider other)
     {    
         //Stardust
         if (other.gameObject.CompareTag("stardust"))
         {
             isActive = 1;
             PlayerPrefs.SetInt("stardust", isActive);           
             active();
             //other.gameObject.SetActive(false);
             levelManager.score++;
             levelManager.setScoreText();
             audioSource.Play();
             PlayerPrefs.SetInt("score", levelManager.score);
         }
     }

     void active()
     {
         if (isActive == 0) //if none are collected
         {
             for (int i = 0; i < stardust.Length; i++)
             {
                 stardust[i].SetActive(true); //make all visible
             }
         }
         if (isActive == 1) //first one collected
         {
             stardust[0].SetActive(false);
             stardust[1].SetActive(false);
             stardust[2].SetActive(false);
         }    
     }
 }

As you can see it sets all of the objects to inactive, how do I check for each one individually ?

I am using a single key in playerprefs for all stardust. Should I rather set a key for each stardust ?

I tried comparing each one by tag, under EventTrigger, with each their own method checking each and setting Active individually to no success


Solution

  • hi Curstin Visagie, it wont work with single key,the playerprefs values will be overwritten ,you have to create each key for each stardust.