UNITY2D:如何使用单例模式销毁先前的对象?

时间:2020-10-23 22:41:51

标签: c# unity3d

我正在做一个项目。它包括两个场景:Maingame和ShopScene。首先,我运行Maingame,有一个天文钟,我就赚钱了。在一天结束时,ShopScene打开。我把钱花在ShopScene上。然后,我单击退出按钮,Maingame再次打开。我使用了“不破坏对象和单例模式”。但是,我的问题是,起初一天是1.我赚了一些钱。我在ShopScene中花了一些钱。在这里,天是2,因为第一天结束了。再次,我来到Maingame场景,但是天又变成1。 Aso我的钱变成0。我以为我的Singleton模式破坏了我的新画布。但是,我希望我的Singleton Pattern破坏先前的画布。我怎样才能做到这一点? 我的代码在这里。

public class EarnMoney : MonoBehaviour
{
    private static EarnMoney instance;
    private int score;
    public Button moneyBarButton;
    public GameObject canvas;
    public int money;
    private GameObject[] boxCountArray;
  
    // Start is called before the first frame update
    void Awake()
    {
        canvas = (GameObject.Find("DontDestroyCanvas"));
      //  DontDestroyOnLoad(canvas);
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(canvas);
        }
        else if (instance != this) {
            Destroy(canvas);
        }
            

   
    }
    void Start()
    {
      //  moneyBarButton = GameObject.Find("MoneyBar").GetComponent<Button>();
    }

    // Update is called once per frame
    void Update()
    {

        SceneManager.SetActiveScene(SceneManager.GetSceneByName("Maingame"));
        PlayerPrefs.GetInt("money");
        moneyBarButton.GetComponentInChildren<Text>().text = Convert.ToString(money);
        score = money / 10;
        boxCountArray = GameObject.FindGameObjectsWithTag("Box");
       // control();
        score =(boxCountArray.Length - 1);//score artışı
        money = (boxCountArray.Length - 1) * 10;
        PlayerPrefs.SetInt("money", money);
    }
}
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 GameObject canvas;
   


    int n = 0;

 
    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);
        moneyBar.GetComponentInChildren<Text>().text = Convert.ToString(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 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);




    }
}

1 个答案:

答案 0 :(得分:1)

如果您希望在场景加载时发生,请不要使用唤醒。而是使用OnSceneLoaded。

void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
    if (string.equal(scene.name, "ShopScene")){
        // Do whatever you want here when the scene loads
        Destroy(canvas)
    }
}