0
votes

I have a scene where I write down my player stats. In the next scene (basically in the next 2 scenes but it doesn't matter) I want to buy some weapons and change the variables.

The thing is I'm saving the object with "DontDestroyOnLoad" and when I go to the next scene I want to find out how can I change the variables.

First Scene:

enter image description here

The code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class statsTextsToDisplayAndChanges : MonoBehaviour
{
    public static statsTextsToDisplayAndChanges _INstance;
    buyWeapons bw;
    public Text m_LevelText;
    public Text m_AttackText;
    public Text m_DefendText;
    public Text m_MoneyText;
    public int level = 0;
    public int money = 500;
    public int health = 400;
    public int attack = 10;
    public int def = 5;
    string answer;
    string url = "http://alex3685.dx.am/display.php";


    public int sword1 = 200;


    public void Start()
    {

        _INstance = this;
        DontDestroyOnLoad(this.gameObject);

        display();

    }

    public void display()
    {


        m_LevelText.text = level.ToString();
        m_AttackText.text = attack.ToString();
        m_DefendText.text = def.ToString();
        m_MoneyText.text = money.ToString();
    }

    public void onPurchase()
    {
        if (money >= sword1)
        {
            Debug.Log("YOU BOUGHT IT");
            money -= sword1;
            //Destroy(GameObject.Find("playerStats"));
            display();
        }
    }

}

Second scene:

enter image description here

When I press the button the debug.log from the purchase function works but in the text nothing changes (from 500 coins-200 coins of the sword=300 coins).

enter image description here

Any ideas?

Thanks in advance.

2
Please show your research/debugging effort so far. Please read How to Ask page first. - Sourav Ghosh

2 Answers

1
votes

Hmmm....initial thoughs:

This is one of the times where you want a true manager object with a scrip attached that only knows how to store the relevant stat.

Then, in whatever scripts that handles the purchasing they have a private GameObject with a reference to the manager object.private GameObject _Manager;

But the object exists in another scene in my editor so I cant drag and drop the reference!

No problem, Lets say that the object with the component that stores the stats are called "PlayerManager". In the script that handles the purchasing in the start() method add: _Manager = gameobject.Find("PlayerManager");

Now you can change all the variables to your hearts content, assuming of course that you have set the variables in the manager to be public, or if you are more advanced and concerned about robust code, you have the proper get;set; methods in place.

Hope this helped!

1
votes