David Marsh
David Marsh

Reputation: 147

trying to save and load a value in c# unity but having trouble

I am trying to get part of my game working but having trouble solving this problem!

I have boosters that remove game pieces if the user has enough in game coins to use. It is working to an extent and once a booster has been used the coins will decrement but upon exiting and reloading the game it does not update the correct value!

For example, the boosters can be used at a cost of 50 coins, if I have 200 coins and use 4 boosters the value updates to 0 and this works. However if I restart then the value of 200 is still there!

I have a coin manager script set up with playerprefs that gives the user 50 coins after each level, this is linked to the booster script.

Booster class:

public class Booster : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler {


    Image m_image;
    RectTransform m_rectXform;
    Vector3 m_startPosition;
    Board m_board;
    Tile m_tileTarget;

    public static GameObject ActiveBooster;
    public Text instructionsText;
    public string instructions = "drag over game piece to remove";

    public bool isEnabled = false;
    public bool isDraggable = false;
    public bool isLocked = false;

    public List<CanvasGroup> canvasGroups;
    public UnityEvent boostEvent;
    public int boostTime = 15;

    //coin test
    CoinManager coinManager;

    private void Awake()
    {
        m_image = GetComponent<Image> ();
        m_rectXform = GetComponent<RectTransform> ();
        m_board = Object.FindObjectOfType<Board> ().GetComponent<Board> ();
        coinManager = GameObject.Find ("CoinManager").GetComponent<CoinManager> ();

    }

    void Start () 
    {
        EnableBooster (false);
    }

    public void EnableBooster(bool state)
    {
        isEnabled = state;

        if (state)
        {
            DisableOtherBoosters ();
            Booster.ActiveBooster = gameObject;
        }
        else if(gameObject == Booster.ActiveBooster)
        {
            Booster.ActiveBooster = null;
        }

        m_image.color = (state) ? Color.white : Color.gray;

        if (instructionsText != null)
        {
            instructionsText.gameObject.SetActive (Booster.ActiveBooster != null);

            if (gameObject == Booster.ActiveBooster)
            {
                instructionsText.text = instructions;
            }
        }
    }

    void DisableOtherBoosters()
    {
        Booster[] allBoosters = Object.FindObjectsOfType<Booster> ();

        foreach (Booster b in allBoosters)
        {
            if (b != this)
            {
                b.EnableBooster (false);
            }
        }
    }

    public void ToggleBooster()
    {
            EnableBooster (!isEnabled);
    }


    public void OnBeginDrag (PointerEventData eventData)
    {
        if (isEnabled && isDraggable && !isLocked)
        {
            m_startPosition = gameObject.transform.position;
            EnableCanvasGroups (false);
        }
    }

    public void OnDrag (PointerEventData eventData)
    {
        if (isEnabled && isDraggable && !isLocked && Camera.main != null)
        {
            Vector3 onscreenPosition;
            RectTransformUtility.ScreenPointToWorldPointInRectangle (m_rectXform, eventData.position,
                Camera.main, out onscreenPosition);

            gameObject.transform.position = onscreenPosition;

            RaycastHit2D hit2D = Physics2D.Raycast (onscreenPosition, Vector3.forward, Mathf.Infinity);

            if (hit2D.collider != null)
            {
                m_tileTarget = hit2D.collider.GetComponent<Tile> ();
            }
            else
            {
                m_tileTarget = null;
            }
        }
    }


    public void OnEndDrag (PointerEventData eventData)
    {
        if (isEnabled && isDraggable && !isLocked)
        {
            gameObject.transform.position = m_startPosition;
            EnableCanvasGroups (true);
            if (m_board != null && m_board.isRefilling)
            {
                return;
            }

            if (m_tileTarget != null)
            {
                if (boostEvent != null)
                {
                    boostEvent.Invoke ();   //can do things here like play a sound effect
                }

                EnableBooster (false);

                m_tileTarget = null;
                Booster.ActiveBooster = null;
            }
        }
    }

    void EnableCanvasGroups(bool state)
    {
        if (canvasGroups != null && canvasGroups.Count > 0)
        {
            foreach (CanvasGroup cGroup in canvasGroups)
            {
                if (cGroup != null)
                {
                    cGroup.blocksRaycasts = state;
                }
            }
        }
    }

    public void RemoveOneGamePiece()
    {
        if (m_board != null && m_tileTarget != null)
        {
            if (coinManager.currentCoinCount >= 50)
            {
                m_board.ClearAndRefillBoard (m_tileTarget.xIndex, m_tileTarget.yIndex);
                coinManager.AddCoins (-50);

                coinManager.SetCoinCount();
                coinManager.ShowCoinCount ();
            }
        }
    }

    public void AddTime()
    {
        if (GameManager.Instance != null)
        {
            if (coinManager.currentCoinCount >= 50){
                GameManager.Instance.AddTime (boostTime);
                coinManager.AddCoins (-50);

                coinManager.SetCoinCount();
                coinManager.ShowCoinCount ();
            }
        }
    }

    public void DropColorBomb()   //big bomb
    {
        if (m_board != null && m_tileTarget != null)
        {
            if (coinManager.currentCoinCount >= 50)
            {
                m_board.MakeColorBombBooster (m_tileTarget.xIndex, m_tileTarget.yIndex);
                coinManager.AddCoins (-50);

                coinManager.SetCoinCount();
                coinManager.ShowCoinCount ();
            }
        }
    }
}

CoinManager class:

public class CoinManager : Singleton<CoinManager>{
    // reference to the UI Text element
    public Text coinText;

    // current number of coins earned during gameplay
    public int currentCoinCount = 0;

    // because we don't have a key set, we should create it and initialize its value to 0
    public void InitCoinCount()
    {
        if (!PlayerPrefs.HasKey("TotalCoins"))
        {
            PlayerPrefs.SetInt("TotalCoins",0);
        }
    }

    // returns the number of coins stored in PlayerPrefs
    public int GetCoinCount()
    {
        if (PlayerPrefs.HasKey("TotalCoins"))
        {
            return PlayerPrefs.GetInt("TotalCoins");
        }

        // if we don't have the key set, so return 0
        return 0;
    }

    // sets a number of coins into PlayerPrefs if the current coin count is greater
    public void SetCoinCount()
    {
        if (PlayerPrefs.HasKey("TotalCoins"))
        {
            int oldCoins = PlayerPrefs.GetInt("TotalCoins"); 
            if (currentCoinCount > oldCoins)
            {
                PlayerPrefs.SetInt("TotalCoins", currentCoinCount);
            }
        }
    }

    // display the coin count as a TextUI
    public void ShowCoinCount()
    {

        if (coinText != null)
        {
            coinText.text = currentCoinCount.ToString();
        }
    }

    //new method for oldcoin count
    public void AddCoins(int coins)
    {
        currentCoinCount = currentCoinCount + coins;
    }
}

Upvotes: 0

Views: 166

Answers (1)

// sets a number of coins into PlayerPrefs if the current coin count is greater

Well, this comment basically tells you the problem. If the coin count isn't greater than what was saved previously, it doesn't save!

Change this:

// sets a number of coins into PlayerPrefs if the current coin count is greater
public void SetCoinCount()
{
    if (PlayerPrefs.HasKey("TotalCoins"))
    {
        int oldCoins = PlayerPrefs.GetInt("TotalCoins"); 
        if (currentCoinCount > oldCoins)
        {
            PlayerPrefs.SetInt("TotalCoins", currentCoinCount);
        }
    }
}

To this:

// sets a number of coins into PlayerPrefs
public void SetCoinCount()
{
    PlayerPrefs.SetInt("TotalCoins", currentCoinCount);
}

Upvotes: 4

Related Questions