Search Unity

Bug Auto duplicate when using PlayerPrefs

Discussion in 'Scripting' started by thekittengun, Mar 30, 2023.

  1. thekittengun

    thekittengun

    Joined:
    Jan 11, 2022
    Posts:
    2
    So i was trying to use PlayerPrefs to save play progess when quit the game
    code use good in all mode but in Game Mode 3 it was auto duplicate my prefabs



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System.Linq;
    5. using UnityEngine.EventSystems;
    6. using UnityEngine.SceneManagement;
    7. using UnityEngine.UI;
    8. using TMPro;
    9.  
    10. public class GameManager : MonoBehaviour
    11. {
    12.      public int _gameMode;
    13.      public List<GameObject> prefabs;
    14.      int index;
    15.      public List<int> num;
    16.      public List<int> _newNum;
    17.      int rnd;
    18.      public float _power;
    19.      public GameObject particleSys;
    20.      public static GameManager instance;
    21.      public TextMeshProUGUI txtNew;
    22.      public GameObject _new;
    23.      float timeDelayMerge = 0.01f;
    24.      public bool canMerge = true;
    25.      float timeTemp;
    26.      float timeTempNew;
    27.      float timeNewDelay = 2f;
    28.      Vector2 newTarget;
    29.      GameObject _2048;
    30.      public List<GameObject> _droppedList;
    31.      public string _name;
    32.  
    33.  
    34.      int _combo = 0;
    35.      public float timeTempCombo;
    36.      public float timeDelayCombo = 0.1f;
    37.  
    38.      GameObject _explode;
    39.      private void Awake()
    40.      {
    41.           instance = this;
    42.      }
    43.      private void Start()
    44.      {
    45.           LoadNewBox();
    46.           _gameMode = PlayerPrefs.GetInt("SellectedMode");
    47.  
    48.           if (PlayerPrefs.GetInt("Played") == 1)
    49.           {
    50.                if (_gameMode == 3)
    51.                {
    52.                     for (int i = 0; i < PlayerPrefs.GetInt("listCount"); i++)
    53.                     {
    54.                          for (int j = 0; j < 3; j++)
    55.                          {
    56.                               _name = i + " " + j;
    57.                               LoadGame(prefabs[j], _name);
    58.                          }
    59.                     }
    60.                }
    61.                else for (int i = 0; i < PlayerPrefs.GetInt("listCount"); i++)
    62.                     {
    63.                          _name = i + " " + _gameMode;
    64.                          LoadGame(prefabs[_gameMode], _name);
    65.                     }
    66.           }
    67.      }
    68.      private void Update()
    69.      {
    70.  
    71.           //Test Zone
    72.  
    73.           //EndTest
    74.           UIManager.instance.Pause();
    75.           if (Time.time - timeTemp > timeDelayMerge)
    76.           {
    77.                canMerge = true;
    78.           }
    79.           if (Time.time - timeTempNew > timeNewDelay)
    80.           {
    81.                _new.SetActive(false);
    82.                txtNew.text = "";
    83.           }
    84.           if (Time.time - timeTempCombo > timeDelayCombo)
    85.           {
    86.                _combo = 0;
    87.           }
    88.      }
    89.      public int droppedCount = 0;
    90.      public void merge(Transform posSpawn, int n, GameObject Box, GameObject detroyedBox, float impactForce)
    91.      {
    92.  
    93.           if (canMerge)
    94.           {
    95.  
    96.                if (GameManager.instance._droppedList.Contains(detroyedBox)) GameManager.instance._droppedList.Remove(detroyedBox);
    97.                if (GameManager.instance._droppedList.Contains(Box)) GameManager.instance._droppedList.Remove(Box);
    98.  
    99.                Vector2 direction = Box.transform.position - detroyedBox.transform.position;
    100.  
    101.                _2048 = Instantiate(TouchManager.instance.objectToSpawn, Box.transform.position, Quaternion.identity);
    102.                _2048.name = TouchManager.instance.objectToSpawn.name;
    103.                _droppedList.Add(_2048);
    104.  
    105.                Destroy(detroyedBox);
    106.                Destroy(Box);
    107.  
    108.                n *= 2;
    109.                if (!num.Contains(n))
    110.                {
    111.  
    112.                     txtNew.text = "New Box: " + n;
    113.                     _new.SetActive(true);
    114.                     if (index > 10) index = 10;
    115.                     SoundManager.instance.PlaySound(3);
    116.                     timeTempNew = Time.time;
    117.                     _newNum.Add(n);
    118.                     num.Add(n);
    119.                }
    120.                SoundManager.instance.PlaySound(2);
    121.  
    122.  
    123.                timeTempCombo = Time.time;
    124.                _combo++;
    125.  
    126.  
    127.                if (_combo == 2)
    128.                {
    129.                     timeTempCombo = Time.time;
    130.                }
    131.                else if (_combo == 3)
    132.                {
    133.                     timeTempCombo = Time.time;
    134.                }
    135.                else if (_combo == 4)
    136.                {
    137.                     timeTempCombo = Time.time;
    138.                }
    139.                else if (_combo >= 5)
    140.                {
    141.                     timeTempCombo = Time.time;
    142.                }
    143.  
    144.  
    145.  
    146.  
    147.  
    148.  
    149.  
    150.                _2048.transform.GetChild(1).gameObject.SetActive(false);
    151.  
    152.                _explode = Instantiate(particleSys, new Vector3(_2048.transform.position.x, _2048.transform.position.y, _2048.transform.position.z - 1), Quaternion.identity);
    153.  
    154.                for (int i = 0; i < num.Count(); i++)
    155.                     if (n == num[i]) index = i;
    156.                _2048.GetComponent<NumberGen>().Init(n, index);
    157.  
    158.  
    159.  
    160.                _2048.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
    161.                _2048.tag = "Dropped";
    162.  
    163.                _2048.GetComponent<Rigidbody2D>().AddForce(direction * impactForce * _power, ForceMode2D.Impulse);
    164.  
    165.  
    166.                UIManager.instance.addScore(n);
    167.  
    168.                timeTemp = Time.time;
    169.                canMerge = false;
    170.           }
    171.  
    172.      }
    173.  
    174.      public void GameOver()
    175.      {
    176.           DeleteKey();
    177.           DeleteNewBox();
    178.           UIManager.instance.LoserPopUp();
    179.           UIManager.instance._pausing = true;
    180.      }
    181.      public int random()
    182.      {
    183.           rnd = Random.Range(0, num.Count() - 1);
    184.           return rnd;
    185.      }
    186.      public int random2048()
    187.      {
    188.           rnd = Random.Range(0, 3);
    189.           return rnd;
    190.      }
    191.      public bool RandomMode(int index)
    192.      {
    193.           if (index == 3)
    194.           {
    195.                return true;
    196.           }
    197.           else return false;
    198.  
    199.      }
    200.      public void SaveNewBox()
    201.      {
    202.           PlayerPrefs.SetInt("Arr.Len", _newNum.Count);
    203.           for (int i = 0; i < PlayerPrefs.GetInt("Arr.Len"); i++)
    204.           {
    205.                PlayerPrefs.SetInt("num" + i, _newNum[i]);
    206.           }
    207.      }
    208.      public void LoadNewBox()
    209.      {
    210.           if (PlayerPrefs.GetInt("Arr.Len") != 0)
    211.           {
    212.                for (int i = 0; i < PlayerPrefs.GetInt("Arr.Len"); i++)
    213.                {
    214.                     if (PlayerPrefs.GetInt("num" + i) != 0)
    215.                     {
    216.                          num.Add(PlayerPrefs.GetInt("num" + i));
    217.                          _newNum.Add(PlayerPrefs.GetInt("num" + i));
    218.                     }
    219.                }
    220.           }
    221.      }
    222.  
    223.      public void SaveGameMix(GameObject _dropped, string _name)
    224.      {
    225.  
    226.      }
    227.      public void SaveGame(GameObject _dropped, string _name)
    228.      {
    229.           PlayerPrefs.SetInt("listCount", _droppedList.Count);
    230.           PlayerPrefs.SetInt("gameMode", _gameMode);
    231.  
    232.           PlayerPrefs.SetFloat(_name + "X", _dropped.transform.position.x);
    233.           PlayerPrefs.SetFloat(_name + "Y", _dropped.transform.position.y);
    234.           PlayerPrefs.SetFloat(_name + "Rot", _dropped.transform.eulerAngles.z);
    235.  
    236.           PlayerPrefs.SetInt("Score", UIManager.instance.score);
    237.           PlayerPrefs.SetInt(_name + "num", _dropped.GetComponent<NumberGen>().number);
    238.  
    239.           PlayerPrefs.SetInt(_name + "color", _dropped.GetComponent<NumberGen>().colornum);
    240.      }
    241.      public void LoadGame(GameObject _dropped, string _name)
    242.      {
    243.           if (PlayerPrefs.GetInt(_name + "num") != 0)
    244.           {
    245.                UIManager.instance._continue.SetActive(true);
    246.                UIManager.instance._pausing = true;
    247.                GameObject _saveddropped;
    248.                _saveddropped = Instantiate(_dropped, new Vector2(PlayerPrefs.GetFloat(_name + "X"), PlayerPrefs.GetFloat(_name + "Y")), Quaternion.Euler(0, 0, PlayerPrefs.GetFloat(_name + "Rot")));
    249.  
    250.  
    251.                _saveddropped.name = _dropped.name;
    252.  
    253.                UIManager.instance.score = PlayerPrefs.GetInt("Score");
    254.                UIManager.instance.txtScore.text = UIManager.instance.score.ToString();
    255.                _saveddropped.tag = "Dropped";
    256.                _saveddropped.GetComponent<NumberGen>().Init(PlayerPrefs.GetInt(_name + "num"), PlayerPrefs.GetInt(_name + "color"));
    257.  
    258.                _saveddropped.transform.GetChild(1).gameObject.SetActive(false);
    259.                _saveddropped.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
    260.                _droppedList.Add(_saveddropped);
    261.           }
    262.  
    263.      }
    264.      public void DeleteNewBox()
    265.      {
    266.           for (int i = 0; i < PlayerPrefs.GetInt("Arr.Len", 0); i++)
    267.           {
    268.                PlayerPrefs.DeleteKey("num" + i);
    269.           }
    270.           PlayerPrefs.DeleteKey("Arr.Leng");
    271.      }
    272.      public void DeleteKey()
    273.      {
    274.           for (int i = 0; i < _droppedList.Count; i++)
    275.           {
    276.                _name = i + " " + GameManager.instance._gameMode;
    277.                PlayerPrefs.DeleteKey(_name + "X");
    278.                PlayerPrefs.DeleteKey(_name + "Y");
    279.                PlayerPrefs.DeleteKey(_name + "Rot");
    280.                PlayerPrefs.DeleteKey("Score");
    281.                PlayerPrefs.DeleteKey(_name + "num");
    282.                PlayerPrefs.DeleteKey(_name + "color");
    283.           }
    284.           PlayerPrefs.DeleteKey("listCount");
    285.  
    286.      }
    287.      private void OnApplicationQuit()
    288.      {
    289.           SaveNewBox();
    290.           if (_gameMode == 3)
    291.           {
    292.                for (int i = 0; i < _droppedList.Count; i++)
    293.                {
    294.                     for (int j = 0; j < 3; j++)
    295.                     {
    296.                          if (_droppedList[i].name == prefabs[j].name)
    297.                          {
    298.                               _name = i + " " + j;
    299.                               SaveGame(_droppedList[i], _name);
    300.                          }
    301.                     }
    302.                }
    303.           }
    304.           else for (int i = 0; i < _droppedList.Count; i++)
    305.                {
    306.                     _name = i + " " + _gameMode;
    307.                     SaveGame(_droppedList[i], _name);
    308.                }
    309.  
    310.      }
    311.  
    312.  
    313.  
    314.  
    315. }
    316.  
     
  2. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    720
    There's way too much going on here! You need to simplify the problem.

    Add Debug.Log statements to each place that asks for prefabs to be instantiated. See what gets logged and decide if each one makes sense or not.
     
    Ryiah and Bunny83 like this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,981
    I would also recommend to use a proper save format and not abuse the player prefs (which are meant to store preferences of the Unity player like volume and things like that). Just storing the data as Json would make much more sense. You can still store the resulting json in a single playerprefs string if you really want. However it makes it much simpler to debug issues with the saved data since you have all the data in one structure.

    You could use my SimpleJSON framework which doesn't require you to create any extra classes. You can simply structure your data much more efficiently. SimpleJSON is just a single file. However I would recommend to also grab the Unity specific extension file. It adds support for Vector3 and some other Unity types which makes the usage even simpler.

    You store individual values all over the place. You should define a single save and a single load method for your save system.
     
    Ryiah likes this.