Search Unity

Game freezes

Discussion in 'Scripting' started by DustyShinigami, Jun 17, 2019.

  1. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    I'm not sure if it's related to my code, but whenever I pick up an item/secret, the game seems to just freeze. I don't know what could be causing it.

    SecretsPickup:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SecretsPickup : MonoBehaviour
    6. {
    7.     public int value;
    8.     public Animator secretAnim;
    9.  
    10.     void Awake()
    11.     {
    12.         secretAnim = GetComponent<Animator>();
    13.     }
    14.  
    15.     public void OnTriggerEnter(Collider other)
    16.     {
    17.         if (other.tag == "Player")
    18.         {
    19.             FindObjectOfType<GameManager>().AddSecret(value);
    20.             Destroy(gameObject);
    21.         }
    22.     }
    23.  
    24.     public IEnumerator SecretRevealed()
    25.     {
    26.         yield return new WaitForSeconds(.5f);
    27.         secretAnim.SetTrigger("secretMove");
    28.     }
    29. }
    GameManager:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using TMPro;
    6.  
    7. public class GameManager : MonoBehaviour
    8. {
    9.  
    10.     public static int currentEmbers;
    11.     public static int currentSecrets;
    12.     public TextMeshProUGUI emberText;
    13.     public TextMeshProUGUI secretsText;
    14.  
    15.     private bool secretCollected = false;
    16.  
    17.     public float timer = 2f;
    18.  
    19.     void Start()
    20.     {
    21.         secretsText.enabled = false;
    22.     }
    23.  
    24.     void Update()
    25.     {
    26.         if (secretCollected)
    27.         {
    28.             secretsText.enabled = true;
    29.             timer -= Time.deltaTime;
    30.             if (timer <= 0f)
    31.             {
    32.                 Time.timeScale = 0;
    33.                 secretsText.enabled = false;
    34.                 secretCollected = false;
    35.             }
    36.         }
    37.     }
    38.  
    39.     public void AddEmber(int embertoAdd)
    40.     {
    41.         currentEmbers += embertoAdd;
    42.         emberText.text = "Embers: " + currentEmbers;
    43.         SetCountText();
    44.     }
    45.  
    46.     public void SetCountText()
    47.     {
    48.         emberText.text = "Embers: " + currentEmbers.ToString();
    49.     }
    50.  
    51.     public void AddSecret(int secrettoAdd)
    52.     {
    53.         secretCollected = true;
    54.         currentSecrets += secrettoAdd;
    55.         secretsText.text = "Secrets Found: " + currentSecrets;
    56.     }
    57. }
    Chest:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class Chest : SecretsPickup
    7. {
    8. public GameObject chest;
    9. public static bool allowOpen;
    10. public GameObject blueSecret;
    11.  
    12. private Animator chestAnim;
    13. private SecretsPickup pickupSecret;
    14.  
    15. void Awake()
    16. {
    17. chestAnim = chest.GetComponent<Animator>();
    18. pickupSecret = blueSecret.GetComponent<SecretsPickup>();
    19. blueSecret.SetActive(false);
    20. }
    21.  
    22. public void OnTriggerEnter(Collider other)
    23. {
    24. if (other.gameObject.CompareTag("Player"))
    25. {
    26. allowOpen = true;
    27. }
    28. }
    29.  
    30. public void ChestOpen()
    31. {
    32. if (allowOpen)
    33. {
    34. chestAnim.SetBool("canOpen", true);
    35. chestAnim.SetTrigger("open");
    36. blueSecret.SetActive(true);
    37. StartCoroutine("SecretRevealed");
    38. }
    39. }
    40. }

    I've noticed the freeze happens after the secret counter text disappears, so I'm guessing it's related to that somehow...?
     
  2. Kwinten

    Kwinten

    Joined:
    Jan 25, 2015
    Posts:
    49
    When is the "ChestOpen" function called? It might be that you're trying to start a coroutine on a GameObject that's already been destroyed.
     
  3. DustyShinigami

    DustyShinigami

    Joined:
    Jan 5, 2018
    Posts:
    529
    Hmm... It looks to be related to Time.timeScale = 0 in the GameManager. And yet, picking up the first secret doesn't cause the game to freeze when that's not commented out. Also, my Secret Counter text doesn't display when another secret is picked up.

    The ChestOpen() function is called in the PlayerController script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class PlayerController : MonoBehaviour
    7. {
    8.     public Animator anim;
    9.     public float moveSpeed;
    10.     public float jumpForce;
    11.     public bool jumped;
    12.     public bool allowInteract = false;
    13.     public float gravityScale;
    14.     public float knockBackForce;
    15.     public float knockBackTime;
    16.     public float invincibilityLength;
    17.     public Renderer playerRenderer;
    18.     public Material textureChange;
    19.     public Material textureDefault;
    20.     public bool allowCombat;
    21.     public bool allowJump;
    22.     public static bool canMove;
    23.     public Chest chest;
    24.  
    25.     [SerializeField]
    26.     private HurtEnemy damageEnemy;
    27.     private Vector2 moveDirection;
    28.     private Vector2 moveHorizontal;
    29.     private Vector2 moveVertical;
    30.     private float knockBackCounter;
    31.     private float invincibilityCounter;
    32.     private CharacterController controller;
    33.     private Quaternion targetRot;
    34.     private bool headingLeft = false;
    35.     private Pickup pickupWeapon;
    36.  
    37.     void Awake()
    38.     {
    39.         controller = GetComponent<CharacterController>();
    40.         anim = GetComponent<Animator>();
    41.     }
    42.  
    43.     void Start()
    44.     {
    45.         Cursor.visible = false;
    46.         pickupWeapon = FindObjectOfType<Pickup>();
    47.         canMove = true;
    48.         targetRot = transform.rotation;
    49.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("start_area"))
    50.         {
    51.             allowCombat = false;
    52.             allowJump = true;
    53.         }
    54.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("hut_interior"))
    55.         {
    56.             allowCombat = false;
    57.             allowJump = false;
    58.         }
    59.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("start_area 2"))
    60.         {
    61.             allowCombat = false;
    62.             allowJump = true;
    63.         }
    64.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("level 1, room 1"))
    65.         {
    66.             allowCombat = true;
    67.             allowJump = true;
    68.         }
    69.         if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("level 1, room 2"))
    70.         {
    71.             allowCombat = true;
    72.             allowJump = true;
    73.         }
    74.     }
    75.  
    76.     void Update()
    77.     {
    78.         if (knockBackCounter <= 0 && canMove)
    79.         {
    80.             moveHorizontal.x = Input.GetAxis("Horizontal");
    81.             float moveHorizontalSnap = Input.GetAxis("Horizontal");
    82.             float moveVertical = Input.GetAxis("Vertical");
    83.             //moveVertical.y = Input.GetAxis("Vertical");
    84.             moveDirection = new Vector2(moveHorizontal.x * moveSpeed, moveDirection.y);
    85.             controller.Move(moveDirection * Time.deltaTime);
    86.  
    87.             //Adds character rotation when changing direction horizontally
    88.             if ((moveHorizontal.x < 0f && !headingLeft) || (moveHorizontal.x > 0f && headingLeft))
    89.             {
    90.                 if (moveHorizontal.x < 0f) targetRot = Quaternion.Euler(0, 270, 0);
    91.                 if (moveHorizontal.x > 0f) targetRot = Quaternion.Euler(0, 90, 0);
    92.                 headingLeft = !headingLeft;
    93.             }
    94.  
    95.             //Adds character rotation when changing direction vertically
    96.             /*if(moveVertical.y < 0f && lookingUp || (moveVertical.y > 0f && !lookingUp))
    97.             {
    98.                 if (moveVertical.y > 0f) targetrot = Quaternion.Euler(0, 0, 0);
    99.                 if (moveVertical.y < 0f) targetrot = Quaternion.Euler(0, 180, 0);
    100.                 lookingUp = !lookingUp;
    101.             }*/
    102.  
    103.             transform.rotation = Quaternion.Lerp(transform.rotation, targetRot, Time.deltaTime * 20f);
    104.  
    105.             if (SceneManagement.insideHut)
    106.             {
    107.                 //Adds character rotation when changing direction horizontally, but snaps instead of fully rotating
    108.                 if (moveHorizontalSnap > 0)
    109.                 {
    110.                     transform.eulerAngles = new Vector2(0, 90);
    111.                 }
    112.                 else if (moveHorizontalSnap < 0)
    113.                 {
    114.                     transform.eulerAngles = new Vector2(0, -90);
    115.                 }
    116.                 //To possibly prevent diagonal movement with some control setups, try adding 'else if'
    117.                 //Adds character rotation when changing direction vertically, but snaps instead of fully rotating
    118.                 else if (moveVertical > 0)
    119.                 {
    120.                     transform.eulerAngles = new Vector2(0, 0);
    121.                 }
    122.                 //Use this to make the character face towards the camera.
    123.                 /*else if (moveVertical < 0)
    124.                 {
    125.                     transform.eulerAngles = new Vector3(0, 180);
    126.                 }*/
    127.             }
    128.  
    129.             if (controller.isGrounded)
    130.             {
    131.                 if (allowJump)
    132.                 {
    133.                     moveDirection.y = -1f;
    134.                     //GetKeyDown will require the player to press the button each time they want to jump. GetKey will allow the player to spam the jump button if they keep pressing it down.
    135.                     if (Input.GetKeyDown(KeyCode.KeypadPlus) || Input.GetKeyDown("joystick button 0"))
    136.                     {
    137.                         moveDirection.y = jumpForce;
    138.                         jumped = true;
    139.                     }
    140.                     else if (!Input.GetKeyDown(KeyCode.KeypadPlus) || !Input.GetKeyDown("joystick button 0"))
    141.                     {
    142.                         jumped = false;
    143.                     }
    144.                 }
    145.  
    146.                 if (allowCombat)
    147.                 {
    148.                     if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown("joystick button 7") || Input.GetKeyDown("joystick button 1"))
    149.                     {
    150.                         playerRenderer.material = textureChange;
    151.                         anim.SetTrigger("Attack");
    152.                     }
    153.                     else if (!Input.GetKeyDown(KeyCode.Space) || !Input.GetKeyDown("joystick button 7") || !Input.GetKeyDown("joystick button 1"))
    154.                     {
    155.                         playerRenderer.material = textureDefault;
    156.                     }
    157.                 }
    158.                 else if (!allowCombat)
    159.                 {
    160.                     playerRenderer.material = textureDefault;
    161.                 }
    162.  
    163.                 if (allowInteract)
    164.                 {
    165.                     if (SceneManagement.xbox360Controller == 1)
    166.                     {
    167.                         if (Input.GetKeyDown("joystick button 2"))
    168.                         {
    169.                             anim.SetBool("Interact", controller.isGrounded);
    170.                             pickupWeapon.ObjectActivation();
    171.                             allowInteract = false;
    172.                         }
    173.                     }
    174.                     else if (SceneManagement.ps4Controller == 1)
    175.                     {
    176.                         if (Input.GetKeyDown("joystick button 0"))
    177.                         {
    178.                             anim.SetBool("Interact", controller.isGrounded);
    179.                             pickupWeapon.ObjectActivation();
    180.                             allowInteract = false;
    181.                         }
    182.                     }
    183.                     else
    184.                     {
    185.                         if (Input.GetKeyDown(KeyCode.Return))
    186.                         {
    187.                             anim.SetBool("Interact", controller.isGrounded);
    188.                             pickupWeapon.ObjectActivation();
    189.                             allowInteract = false;
    190.                         }
    191.                     }
    192.                 }
    193.                 if(Chest.allowOpen)
    194.                 {
    195.                     if (SceneManagement.xbox360Controller == 1)
    196.                     {
    197.                         if (Input.GetKeyDown("joystick button 2"))
    198.                         {
    199.                             anim.SetBool("Interact", controller.isGrounded);
    200.                             chest.ChestOpen();
    201.                             allowInteract = false;
    202.                         }
    203.                     }
    204.                     else if (SceneManagement.ps4Controller == 1)
    205.                     {
    206.                         if (Input.GetKeyDown("joystick button 0"))
    207.                         {
    208.                             anim.SetBool("Interact", controller.isGrounded);
    209.                             chest.ChestOpen();
    210.                             allowInteract = false;
    211.                         }
    212.                     }
    213.                     else
    214.                     {
    215.                         if (Input.GetKeyDown(KeyCode.Return))
    216.                         {
    217.                             anim.SetBool("Interact", controller.isGrounded);
    218.                             chest.ChestOpen();
    219.                             allowInteract = false;
    220.                         }
    221.                     }
    222.                 }
    223.             }
    224.         }
    225.         else
    226.         {
    227.             knockBackCounter -= Time.deltaTime;
    228.         }
    229.  
    230.         moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale * Time.deltaTime);
    231.  
    232.         anim.SetBool("isGrounded", controller.isGrounded);
    233.         //If the character can't move, then the Speed is set to 0. Otherwise it'll use the horizontal input value.
    234.         anim.SetFloat("Speed",
    235.             !canMove
    236.             ? 0f
    237.             : Mathf.Abs(Input.GetAxis("Horizontal")));
    238.  
    239.         //anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
    240.  
    241.         /*if (interact)
    242.         {
    243.             if (Input.GetKeyDown(KeyCode.Return))
    244.             {
    245.                 anim.SetBool("Interact", controller.isGrounded);
    246.                 FindObjectOfType<Pickup>().ObjectActivation();
    247.                 interact = false;
    248.                 allowInteract = false;
    249.             }
    250.         }*/
    251.     }
    252.  
    253.     public void Knockback(Vector3 direction)
    254.     {
    255.         knockBackCounter = knockBackTime;
    256.  
    257.         moveDirection = direction * knockBackForce;
    258.         moveDirection.y = knockBackForce;
    259.     }
    260. }
     
  4. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    394
    Setting Time.timeScale to 0 stops all physics and animation from happening. Time.deltaTime will return 0, meaning most of your input will stop working if you set it up to be framerate independent by multiplying by deltaTme. It makes time stop. Is that the sort of freeze you are seeing?
     
  5. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    FindObjectOfType and following Destroy might be the sources of your freeze. Use singletong instead of find and hide object instead of destroying it. If after that freezes won't go away, click Window > Analysis > Profiler and check what else cosumes frame time on freezes.