1
public class ShopManager : MonoBehaviour
{
    // Start is called before the first frame update

    public Button itemBuyButton; //Almak istediğim itemin butonu.
    public Button moneyBar; //Para kutucuğu
    int price; //İslem yapabilmek için para kutucuğumdaki text i double a çeviricem. Bu değişken onu tutmak için.
    public Transform floatingText; //item aldığımda aldığım itemin fiyatının ekranda çıkmasını temsil eden object
    public Transform infoAboutShop; // item aldığımda itemden kaç tane aldığımı ekrana yazdıran object.
    public Canvas canvas;

  
    int n = 0;

    public void Awake()
    {
        DontDestroyOnLoad(canvas);
    }
    void Start()
    {
      //price = PlayerPrefs.GetInt("money");
        moneyBar = GameObject.Find("MoneyBar").GetComponent<Button>();
      
    } 

    // Update is called once per frame
    void Update()
    {
        //Butonların interaktifliği sürekli kontrol edilsin istediğimden ilgili methodu update metodumda çağırıyorum.
        
        buttonInteractable();
        PlayerPrefs.SetInt("money", price);
    }

    public void buy()
    {
        //floatingText objemin TextMesh componentine ilgili itemin fiyatını atıyorum.
        floatingText.GetComponent<TextMesh>().text = itemBuyButton.GetComponentInChildren<Text>().text;
        /*
        *Instantiate metodu clone yaratmaya yarıyor. floatingText objemden clone yaratıcam. Clonenun yaratılmasını istediğim yeri tıkladığım yer olarak belirttim.
        *Quaternion identity ise rotation olmadan ilgili objenin clonelamasını sağlıyor. Bu cloneun TextMesh componentine de aynı şekilde ilgili itemin fiyatını atıyorum.
        * Bu işlemleri buy metodunun içinde yapmamın nedeni de floatingText lerin item satın alındığında oluşacak olması.
        */
        Instantiate(floatingText, new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z), Quaternion.identity).GetComponent<TextMesh>().text = itemBuyButton.GetComponentInChildren<Text>().text;


        //Para kutucuk butonumun text componentini double a çevirip yukarıda oluşturduğum moneyBarPrice değişkenine atıyorum. İşlemleri bu değişken üzerinden yapacağım.
        price = Convert.ToInt32(moneyBar.GetComponentInChildren<Text>().text);

        //Butonun text componentine ulaşıp aynı şekilde o text i de kıyaslama yapabilmek için double a çeviriyorum.
        if (price >= (Convert.ToDouble(itemBuyButton.GetComponentInChildren<Text>().text)))

        {
            // item aldıktan sonra itemin fiyatını total fiyatımdan düşüyorum.  
            price -= (Convert.ToInt32(itemBuyButton.GetComponentInChildren<Text>().text));
            // kalan fiyatımı string e çevirip para kutucuğuma yazıyorum.
            moneyBar.GetComponentInChildren<Text>().text = Convert.ToString(price);


            //infoAboutShop objemin TextMesh componentine ilgili itemin adını ve sayısını atıyorum.
            infoAboutShop.GetComponent<TextMesh>().text = Convert.ToString(n + 1) + " " + itemBuyButton.name;
            //floatingText teki mantıkla infoAboutShop objelerimi (200,200) konumunda clonelayıp ilgili nesnenin adı ve sayısını atıyorum.
            Instantiate(infoAboutShop, new Vector2(200, 200), Quaternion.identity).GetComponent<TextMesh>().text = infoAboutShop.GetComponent<TextMesh>().text;
            //her çağırıldığında ilgili objenin sayısını 1 artırıyorum.
            n += 1;

        }
        else
        {
            // eğer iteme tıkladıktan sonra param tıkladığım itemi almaya yetmiyorsa itemin aktifliği engelleniyor.
            itemBuyButton.interactable = false;
        }

    }

    void buttonInteractable()
    {
        price= Convert.ToInt32(moneyBar.GetComponentInChildren<Text>().text);
        Debug.Log(price);
        //Butonun text componentine ulaşıp aynı şekilde o text i de kıyaslama yapabilmek için double a çeviriyorum.
        if (price >= (Convert.ToDouble(itemBuyButton.GetComponentInChildren<Text>().text)))

        {
            itemBuyButton.interactable = true; // Eğer  start butonu aktif eğilse ve param almak istediğim itemden fazlaysa butonun aktifliği devam eder.
        }
        else
        {
            itemBuyButton.interactable = false; //  param tıkladığım itemi almaya yetmiyorsa itemin aktifliği engelleniyor.
        }
    }


   
}
public class DragandDrop : MonoBehaviour
{
    public GameObject box;
    public GameObject table;
    public Text scoreText;
   public Button moneyBarButton;
    public Canvas canvas;
    public int money;

    private bool isFit;
    private bool isMoving;

    private float startPosX;
    private float startPosY;
    private GameObject [] boxCountArray;
    private GameObject[] moneyCountArray;
    private Vector3 startPosition;

     void Awake()
    {
       
        DontDestroyOnLoad(canvas);
    }
    // Start is called before the first frame update
    void Start()
    {
       
        startPosition = this.transform.localPosition;
      moneyBarButton= GameObject.Find("MoneyBar").GetComponent<Button>();
        


    }

    // Update is called once per frame
    void Update()
    {
        // moneyBarButton = GameObject.Find("MoneyBar").GetComponent<Button>();
        SceneManager.SetActiveScene(SceneManager.GetSceneByName("Maingame"));
        PlayerPrefs.GetInt("money");
        moneyBarButton.GetComponentInChildren<Text>().text = Convert.ToString(money);
        scoreText.text = "Score: " + money / 10;
        boxCountArray = GameObject.FindGameObjectsWithTag("Box");
        control();
        scoreText.text = "Score: " + (boxCountArray.Length-1);//score artışı
        money = (boxCountArray.Length - 1) * 10;

        
        //moneyBarButton = GameObject.Find("MoneyBar").GetComponent<Button>();

    }
    public bool control() {
        if (!isFit)
        {
            if (isMoving)
            {
                
                Vector3 mousePos = Input.mousePosition;
                mousePos = Camera.main.ScreenToWorldPoint(mousePos);
                
                this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, this.gameObject.transform.localPosition.z);
                return true;
            }
            return false;
        }
        return false;
    }
     void moneyIncrease() {
        
        while (control() == true)
        {
            
            money += 10;
            moneyBarButton.GetComponentInChildren<Text>().text = money.ToString();//para artışı
            PlayerPrefs.SetInt("money", money);
            break;
        }
    
    
    
    }

    private void OnMouseDown()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePos = Input.mousePosition;
            mousePos = Camera.main.ScreenToWorldPoint(mousePos);

            startPosX = mousePos.x - this.transform.localPosition.x;
            startPosY = mousePos.y - this.transform.localPosition.y;

            isMoving = true;
        }
    }

    private void OnMouseUp()
    {
        isMoving = false;

        if (Mathf.Abs(this.transform.localPosition.x - table.transform.localPosition.x) <= 0.5f &&
            Mathf.Abs(this.transform.localPosition.y - table.transform.localPosition.y) <= 0.5f)
        {
            Vector3 position = new Vector3(UnityEngine.Random.Range(-11,1 ), UnityEngine.Random.Range(-3, 4), transform.position.z);//Yeni oluşacak boxun pozisyonunu random belirler.
            this.transform.position = new Vector3(box.transform.position.x, box.transform.position.y, box.transform.position.z);
            Instantiate(box,position ,Quaternion.identity);//Her kutu masaya yerleştiğinde yeni bir kutu oluşturur
            
            isFit = true;
        }
        else
        {
            this.transform.localPosition = new Vector3(startPosition.x, startPosition.y, startPosition.z);
        }
    }


}
public class closedButton : MonoBehaviour
{
    Scene scene;
  public Button moneyBar;
   
    

    // Start is called before the first frame update
    void Start()
    {

        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void ExitShop()
    {
        SceneManager.GetActiveScene();

        SceneManager.LoadScene(0);




    }
}
public class DragandDrop : MonoBehaviour
{
   private static DragandDrop instance;
    public GameObject box;
    public GameObject table;
    public Text scoreText;
   public Button moneyBarButton;
    public GameObject canvas;
    public int money;

    private bool isFit;
    private bool isMoving;

    private float startPosX;
    private float startPosY;
    private GameObject [] boxCountArray;
    private GameObject[] moneyCountArray;
    private Vector3 startPosition;

     void Awake()
    {
        canvas = (GameObject.Find("DontDestroyCanvas"));
        DontDestroyOnLoad(canvas);
        if (instance == null)
        {
            instance = this; 
            DontDestroyOnLoad(canvas);
        }
        else if (instance != this)
            Destroy(canvas);

    }

I am working on a project. Think that there are two different scenes. One is ShopScene, another is Maingame scene. There is a button in Maingame scene that shows my money. Also in this scene, I earn money and money increase in this button. Then I change the scene. In ShopScene, I can see the money that I earn and I can buy sth. Of course, my money decreases. However, when I change the scene again, when I opened the Maingame scene, my money becomes 0.

How do I make the amount of money the same between the ShopScene and the Maingame scene?

Drag and drop script for Maingame, shop manager for ShopScene. Alsı close button closes the shop and opens the Maingame. At the end of codes I added my singleton codes which is not working

cer
  • 33
  • 7
  • Then your code is wrong. A don’t destroy on load object will stay unless you manually destroy it – BugFinder Oct 20 '20 at 20:00
  • I'd suggest perhaps checking out using Unity's PlayerPrefs to store these kinds of values as I'd guess you wouldn't want money to reset after you refresh the game. Also please share your code. – Harry Oct 20 '20 at 20:02
  • @Harry I added my codes. In Maingame scene everything is OK. Also in running time when I open the ShopScene OK. However, when I opened Maingame again everyting becomes 0. – cer Oct 20 '20 at 21:12
  • If you use `DontDestroyOnLoad` you should at the same time make also sure that a) There are no multiple instances at the same time (Singleton Pattern) and b) That everything else from the scene will be able to again get the reference after the scene reload -> you can "abuse" the Singleton Pattern for this and provide the reference as `public static`. – derHugo Oct 20 '20 at 22:55

1 Answers1

0

It seems that you have two canvases. One on your maingame scene and one on the shopscene. If your game starts on the Maingame first before your shop scene. I'd suggest you to find the object in your awake method instead of creating a completely separate object by using GameObject.Find(). This will ensure that the proper canvas is selected and put in DontDestroyOnLoad because it seems that you are saving the home screen canvas with money of 0 on the home screen which you would not want. The awake method should probably look something like this:

public void Awake()
{
    canvas = GameObect.Find('Canvas');//Canvas would be replaced by the gameobjects name
    DontDestroyOnLoad(canvas);
}
Harry
  • 624
  • 5
  • 14
  • When the Maingame is loaded, have a game manager that will instansiate the prefab for the canvas if there isn't already a canvas in game. – Harry Oct 24 '20 at 16:56