• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Ryujose · Aug 17, 2014 at 08:16 PM · playerprefssavelives

PlayerPrefs, First time applying and need help.

Hello community.

I want to save lives after the level is restarted by pressing a button, I've applied PlayerPrefs but it do nothing on the practice.

Here I'll copy my scripts.

 using UnityEngine;
 using System.Collections;
 
 public class VidaScript : MonoBehaviour {
 
     //Interfaz Grafica Vida
     
     public int vida = 2;
     public GUIText LivesText;
 
     //Prueba
 
     public static string Vidas;
 
 
 
     void Start () {
 
         UpdateVida ();
     }
     
 
     public void Subtract (int newValueVida)
     {
         vida -= newValueVida;
         UpdateVida ();
         PlayerPrefs.SetInt (Vidas, newValueVida);
 
     }
     void UpdateVida ()
     {
         
         LivesText.text = "Lives: " + vida;
     }
 }

And the other script.

using UnityEngine; using System.Collections;

/// Script despues de morir

public class GameOverScript : MonoBehaviour {

 private VidaScript vidaScript;
 private int lives;

 void Start ()
 {
             GameObject vidaScriptObject = GameObject.FindGameObjectWithTag ("VidaScript");
             if (vidaScriptObject != null) {
                     vidaScript = vidaScriptObject.GetComponent <VidaScript> ();
             }
             if (vidaScript == null) {
                     Debug.Log ("No se puede encontrar VidaScript");
             }    

     }




 void OnGUI()
 {
     const int anchoBoton = 140;
     const int altoBoton = 60;
     
     if (
         GUI.Button(
         new Rect(
         Screen.width / 2 - (anchoBoton / 2),
         (1 * Screen.height / 3) - (altoBoton / 2),
         anchoBoton,
         altoBoton
         ),
         "Restart level"
         )
         )
     {
         // Reiniciamos el nivel y no destruimos.
         Application.LoadLevel(Application.loadedLevel);
         PlayerPrefs.GetInt(VidaScript.Vidas);
     }
     
     if (
         GUI.Button(
         new Rect(
         Screen.width / 2 - (anchoBoton / 2),
         (2 * Screen.height / 3) - (altoBoton / 2),
         anchoBoton,
         altoBoton
         ),
         "Back to MainScreen"
         )
         )
     {
         // Vamos a Menu
         Application.LoadLevel("StartScene");
     }
 }

}

If somebody can explain to me, why it don't work and how it works, I'll really appreciate it.

Thanks a lot for your help.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Ryujose · Aug 22, 2014 at 07:20 PM

I've done it in a diferrent way. And it works perfect! Thanks for the help, Steel_Arm you guide me in the way.

Here's my code.

 using UnityEngine;
 using System.Collections;
 
 public class VidaScript : MonoBehaviour {
 
     //Interfaz Grafica Vida
     
     public int vida = 0;
     private static int vidasIniciales = 2;
     private static int vidasActuales;
     public GUIText LivesText;
 
     //Prueba
 
 
     static VidaScript ()
     {
         vidasActuales = PlayerPrefs.GetInt("lives", vidasIniciales);
     }
 
     public static int VidasActuales {
                 get { return vidasActuales; }
                 set {
                         vidasActuales = Mathf.Max (0, value); // Para que no de negativo.
                         PlayerPrefs.SetInt ("lives", vidasActuales);
                 }
         }
 
     void Start () 
     
     {
         vidasActuales = PlayerPrefs.GetInt("lives", vidasIniciales);
         UpdateVida ();
 
     }
 
 
 
     public void Subtract (int newValueVida)
     {
         vida -= newValueVida;
         UpdateVida ();
 
 
     }
     void UpdateVida ()
     {
         
         LivesText.text = "Lives: " + vidasActuales.ToString ();
     }
 
     public void drecrementoVidas ()
     {
                 vidasActuales--;
         PlayerPrefs.SetInt("lives", vidasActuales);
         }
     public void incrementoVidas ()
     {
                 vidasActuales++;
         PlayerPrefs.SetInt("lives", vidasActuales);
 
         }
     public void zeroVidas()
     {
         if (VidaScript.vidasActuales > 0)
             Application.LoadLevel("StartScene");
     }
 }
 

 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
2

Answer by Steel_Arm · Aug 17, 2014 at 08:23 PM

Change this:

 PlayerPrefs.SetInt (Vidas, newValueVida);

to be this:

 PlayerPrefs.SetInt (Vidas, vida);

And this:

 PlayerPrefs.GetInt(VidaScript.Vidas);

should instead be this:

 vidaScript.vida = PlayerPrefs.GetInt(VidaScript.Vidas);

That should do it.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ryujose · Aug 18, 2014 at 03:13 PM 0
Share

Thanks for helping me, but It doesn't work.

I've this too in my script of health. Maybe it cause some error and restart the value?

     //Llamamos al VidaScript y a un int para newValueVida
     
     private VidaScript vidaScript;
     private int lives = 1;
     
     /// Es jugador o enemigo?
 
     public bool esEnemigo = true;
 
     void Start ()
     {
         GameObject vidaScriptObject = GameObject.FindGameObjectWithTag ("VidaScript");
         if (vidaScriptObject != null) {
             vidaScript = vidaScriptObject.GetComponent <VidaScript>();
         }
         if (vidaScript == null) {
             Debug.Log ("No se puede encontrar VidaScript");
         }    
     }
     
     void OnTriggerEnter2D(Collider2D collider)
     {
         //Es un disparo?
         Disparar disparo = collider.gameObject.GetComponent<Disparar>();
         if (disparo != null)
         {
             // Revisamos si es enemigo o compañero
             if (disparo.esDisparoEnemigo != esEnemigo)
             {
                 ps -= disparo.daño;
                 
                 // Destruimos el disparo
                 // No colocar solo Destroy()
                 //sino eliminara el Script
                 Destroy(disparo.gameObject);
                 
                 if (ps <= 0)
                 {
                     // Muerto + EfectoEspecial de particulas
                     vidaScript.Subtract(lives);
                     EfectosEspecialesScript.Instancia.Explosion(transform.position);
                     EfectosDeSonido.Instancia.ReproducirSonidoExplosion();
                     Destroy(gameObject); 
 
avatar image Steel_Arm · Aug 22, 2014 at 05:57 AM 0
Share

Well, I don't see a place where you initialize the value of "vida". When you start a new game, you need to set the value of "vida" to something. Possibly, you could do this in vidaScript:

 void Start() {
     if (PlayerPrefs.HasKey(Vidas) == true) {
         vida = PlayerPrefs.GetInt(Vidas);
     }
     else {
         vida = 3; // set as whatever you want for initial lives.
     }
 }

And make sure you don't make VidaScript persistent, so it reloads with a level reload. With that, you change this:

 // Reiniciamos el nivel y no destruimos.
 Application.LoadLevel(Application.loadedLevel);
 PlayerPrefs.GetInt(VidaScript.Vidas);


To be just this:

 // Reiniciamos el nivel y no destruimos.
 Application.LoadLevel(Application.loadedLevel);

If I remember correctly, I think Application.LoadLevel() doesn't return anyways, so that line about PlayerPrefs.GetInt() is never reached. But I could be wrong. Either way, this should work. I think.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

PlayerPrefs HighScore problems, it doesn't work. 4 Answers

PlayerPrefs - Can I save more than one? 1 Answer

Loading error when using PlayerPrefs.GetInt with WebPlayer 2 Answers

PlayerPrefs 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges