Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Bool stuck as true through scenes.

Discussion in 'Scripting' started by Erin abrams, Jun 1, 2015.

  1. Erin abrams

    Erin abrams

    Joined:
    Mar 4, 2015
    Posts:
    22
    Ok so the main part of this script is supposed to do the following: if the player clicks on a cube and the players coin count >= to the amount of coins the cubes costs then it will set isPurchased = 1 (true). But if I set a cubes bool in the inspector to 0 and then go to the main menu and return to that scene it's back to true (1). So it's basically defaulting to false. Please find out why.
    using UnityEngine;

    using System.Collections;


    public class RedButton : MonoBehaviour {

    public int pointsToAdd;

    public int isPurchased;

    public int pointsToSubtract;

    public Texture textureToChangeTo;

    int zero;


    void Start () {


    isPurchased = PlayerPrefs.GetInt ("purchase");


    ScoreManager.score = PlayerPrefs.GetInt ("CurrentScore");

    zero = 0;

    }





    public void OnMouseDown()

    {

    if (isPurchased == 0 && ScoreManager.score >= pointsToSubtract) {

    ScoreManager.score -= pointsToSubtract;



    PlayerPrefs.SetInt ("CurrentScore", ScoreManager.score);


    PlayerPrefs.SetInt ("purchase", 1);

    isPurchased = PlayerPrefs.GetInt ("purchase");

    Debug.Log ("You purchased a thingy");





    } else if (isPurchased == 1) {

    Debug.Log ("You have already purchased this thing");

    ScoreManager.score += zero;

    } else if (PlayerPrefs.GetInt ("purchase") == 0 && ScoreManager.score < pointsToSubtract)


    Debug.Log ("not enough coins");







    }


    }
     
  2. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Please edit your post and put the code in [ CODE][ /CODE] tags (without the spaces) and formatted/indented properly - It's just too difficult to read otherwise.
     
  3. magnetix

    magnetix

    Joined:
    Apr 4, 2010
    Posts:
    102
    The Start() method is reading the value from the PlayerPrefs, which are persistent between sessions. So regardless of how the value is set in the inspector, the value gets overwritten on start up everytime, depending on what value was saved into PlayerPrefs.

    Also, larku is correct: please use code tags when posting code or people will most likely ignore your question.