How can I optimize my code? THANKS EVERYONE

I’ve been struggling with this issue for five days straight, without taking a break. Just as I get close to fixing the problem, it reoccurs! Let me describe the problem I’m facing:

The main element in my scenario is a plane, which represents my character. After analyzing the profiler, it’s evident that the player is the most critical aspect causing disruptions in the game. Additionally, the profiler also indicates the editor utilizing a significant amount of RAM and resources, leading me to consider Unity as a potential factor. Unfortunately, my attempt to resolve the issue by creating a build didn’t yield positive results – in short, it didn’t work.

Initially, my game was progressing smoothly without any problems. My plan was on track, with only the addition of sounds, visual effects (FX), user interface (UI), and graphics left to complete. I began by implementing sound effects. While the rocket explosion sound functioned for about a minute, it subsequently triggered a game crash. I dedicated two entire days to addressing this issue, and I managed to resolve it. I felt a sense of accomplishment, which motivated me to tackle the remaining sound effects. However, this optimism was short-lived, as the crashes persisted. This repetitive cycle of opening Unity, making adjustments, testing, encountering crashes (occasionally resulting in Unity crashing and even affecting my PC if left open), and repeating the process has left me extremely frustrated. Dealing with this ordeal is causing a decline in my sanity.

I’m desperately seeking solutions, advice, or any insights you might have. My current approach involves sifting through numerous articles and delving into scripting APIs, which is proving to be mentally taxing.

While occasional crashes related to enemy entities have been observed, they are relatively manageable and can often be resolved. However, the real challenge lies in addressing the errors within the player script. Surprisingly, Visual Studio isn’t indicating any issues.

Regarding performance, the FPS (frames per second) in the profiler used to stay consistently between 1000 and 1010 FPS. Upon adding the rocket explosion, the FPS dropped to a range of 100 to 120, which was still acceptable. However, after implementing the “ucakdus” sound, FPS plummeted to values between 15, 30, and occasionally 60, with frequent spikes within the 15-30 range. These spikes eventually lead to a complete freeze of the game, accompanied by a system crash.

HERE IS THE CODE:

using System.Collections;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public AudioSource propellerSound;
    public AudioSource gameMusic;
    private GameManager gameManager;
    public Camera Camera;
    public GameObject plane;
    public GameObject propeller;
    [SerializeField] private Rigidbody rb;
    public GameObject algila;  //ALGILA means DETECT

    public Vector3 rotation;
    public Vector3 worldPos;
    public Vector3 offset;
    public Vector3 currentVelocity;

    public int health;

    public float horizontalInput;
    public float verticalInput;
    public float count = 0;
    [SerializeField] private float speed;
    public float currentSpeed;
    [SerializeField] private float turningSpeed = 0.5f;
    public float smoothTime = 0.25f;
    public float cameraSpeed;
    public float currentAmmo = 250;

    private bool isHoldingW = false;
    private bool isHoldingSpace = false;
    private bool isHoldingR = false;
    public bool rotationAlright = false;
    public bool movePlaneForward = false;
    public bool dashHappened = false;
    public bool canMove = true;
    public bool useAlternativeControls;

    public Material vinyet;

    public GameObject spawnPlace1;
    public GameObject spawnPlace2;
    public GameObject spawnPlace3;
    public GameObject spawnPlace4;

    public GameObject rocketSpawnPlace1;
    public GameObject rocketSpawnPlace2;

    public GameObject bullet1;
    public GameObject rocket1;

    public GameObject bulletParent;
    public GameObject rocketParent;

    public AudioSource mermiSes;

    public CheckFront checkFront;

    public float standartTimeRemaining = 2;
    public float timeRemaining;

    private int whichSideRocketSpawn = 1;

    private int bulletCount;
    private int rocketCount;

    public bool shouldSpawn;
    public bool shouldRocketSpawn;

    public AudioSource ucakDus;

    //private bool motorOverClocked = false;

    private void Start()
    {
        gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();

        rb = GetComponent<Rigidbody>();

        ConfinedCursor();

        Camera = Camera.main;

        shouldSpawn = false;

        timeRemaining = standartTimeRemaining;

        checkFront = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<CheckFront>();

     
    }


    private void Update()
    {


        

        if (this != null)
        {
            //Debug.Log(GameObject.FindGameObjectWithTag("Bina").name);

            horizontalInput = Input.GetAxis("HorizontalAD");
            verticalInput = Input.GetAxis("VerticalW");

            float rotateHorizontal = Input.GetAxis("Mouse X");
            float rotateVertical = Input.GetAxis("Mouse Y");

            float alternativeRotateHorizontal = Input.GetAxis("ArrowsLeftRight");
            float alternativeRotateVertical = Input.GetAxis("ArrowsUpDown");

            currentSpeed = Mathf.RoundToInt(rb.velocity.magnitude * 2.237f);

            propeller.transform.Rotate(0, 0, currentSpeed);

            propellerSound.volume = 0.5f;

            if (isHoldingW)
            {
                propellerSound.volume += Time.deltaTime * 6;
                propellerSound.loop = true;
            }
            else
            {
                propellerSound.volume -= Time.deltaTime;
                propellerSound.loop = false;
            }

            if (Input.GetKeyDown(KeyCode.Q))
            {
                ConfinedCursor();
            }
            if (Input.GetKeyDown(KeyCode.E))
            {
                EscapedMouse();
            }

            if (Input.GetKeyDown(KeyCode.N))
            {
                useAlternativeControls = !useAlternativeControls;
            }

            if (gameManager.gameIsPlayable)
            {
                transform.Rotate(rotation * turningSpeed);

                transform.Rotate(0, horizontalInput * turningSpeed, 0);

                isHoldingW = Input.GetKey(KeyCode.W);

                if (isHoldingW && currentSpeed < 200 && canMove)
                {
                    move();
                }

                if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
                {
                    if (!dashHappened)
                    {
                        dash();
                        //Debug.Log("Dash happened!");
                    }
                }

                if (dashHappened)
                {
                    StartCoroutine(DashCooldown());
                }

                isHoldingSpace = Input.GetKey(KeyCode.Space);

                if (isHoldingSpace)
                {
                    shouldSpawn = true;
                }
                else
                {
                    shouldSpawn = false;
                }

                isHoldingR = Input.GetKeyDown(KeyCode.R);

                //This will detect clicking not holding, I will fix it's name later.
                if (isHoldingR)
                {
                    shouldRocketSpawn = true;
                }
                else
                {
                    shouldRocketSpawn = false;
                }

                if (rotationAlright)
                {
                    if (useAlternativeControls)
                    {
                        rotation = new Vector3(alternativeRotateHorizontal * 2, 0.0f, alternativeRotateVertical * 2);
                    }
                    else
                        rotation = new Vector3(rotateHorizontal, 0.0f, rotateVertical);
                }
                else
                {
                    rotation = Vector3.zero;
                }

              
               
            }
        }
        Quaternion rotateCorrect = new Quaternion(this.transform.rotation.x, this.transform.rotation.y, this.transform.rotation.z, this.transform.rotation.w);
        Quaternion rotateCorrectRocket = new Quaternion(this.transform.rotation.x, this.transform.rotation.y - 93, this.transform.rotation.z, this.transform.rotation.w);

        /*if (algila.GetComponent<Algila>().timeHasSlowed)
        {
            mermiSes.pitch = 0.5f;
        }
        else
        {
            mermiSes.pitch = 1.0f;
        }*/

        bulletCount = GameObject.FindGameObjectsWithTag("Bullet").Length;
        if (shouldSpawn && bulletCount < 50 && this.rotationAlright)
        {
            Instantiate(bullet1, spawnPlace1.transform.position, rotateCorrect, bulletParent.transform);
            Instantiate(bullet1, spawnPlace2.transform.position, rotateCorrect, bulletParent.transform);
            Instantiate(bullet1, spawnPlace3.transform.position, rotateCorrect, bulletParent.transform);
            Instantiate(bullet1, spawnPlace4.transform.position, rotateCorrect, bulletParent.transform);
        }

        rocketCount = GameObject.FindGameObjectsWithTag("Rocket").Length;
        if (shouldRocketSpawn && rocketCount < 2 && this.rotationAlright)
        {
            if (whichSideRocketSpawn == 1)
            {
                Instantiate(rocket1, rocketSpawnPlace1.transform.position, rotateCorrectRocket, rocketParent.transform);

                whichSideRocketSpawn = 0;
            }
            else
            {
                Instantiate(rocket1, rocketSpawnPlace2.transform.position, rotateCorrectRocket, rocketParent.transform);

                whichSideRocketSpawn = 1;
            }
        }

        if (movePlaneForward && this)
        {
            move();
        }

        //MOST PROBLEMATIC PLACE

        if (health <= 0)
        {
            die();
        }

        //MOST PROBLEMATIC PLACE
    }

    private void move()
    {
        rb.AddRelativeForce(Vector3.left * speed * verticalInput);
        //speed += Time.deltaTime /2;
    }

    private void dash()
    {
        rb.AddRelativeForce(Vector3.left * currentSpeed / 1.5f * verticalInput, ForceMode.Impulse);
        dashHappened = true;
    }

    private void ConfinedCursor()
    {
        Cursor.lockState = CursorLockMode.Confined;

        gameManager.gameIsPlayable = true;

        Cursor.visible = false;

        movePlaneForward = false;
    }

    private void EscapedMouse()
    {
        Cursor.lockState = CursorLockMode.None;

        gameManager.gameIsPlayable = false;

        Cursor.visible = true;
    }

    private IEnumerator DashCooldown()
    {
        yield return new WaitForSeconds(5);

        //Debug.Log("Dash is ready!");

        dashHappened = false;
    }

//MOST PROBLEMATIC PLACE

    private IEnumerator die()
    {
        ucakDus.Play();

        if (!ucakDus.isPlaying)
        {
            yield return new WaitForSeconds(2);
            gameManager.gameIsPlayable = false;
        }
    }

//MOST PROBLEMATIC PLACE

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground") && this != null)
        {
            rotationAlright = false;
        }
        else if (collision.gameObject.CompareTag("TESTPLACE") && this != null)
        {
            rotationAlright = true;
        }
        else if (collision.gameObject.CompareTag("EnemyRocket"))
        {
            health = health - 10;
            Destroy(collision.gameObject);
        }
        else if (collision.gameObject.CompareTag("EnemyPlaneRocket"))
        {
            health = health - 10;
            Destroy(collision.gameObject);
        }
        else if (collision.gameObject.CompareTag("EnemyBullet") && this != null)
        {
            health--;
        }
        else if (collision.gameObject.CompareTag("Enemy") && this != null)
        {
            gameObject.GetComponents<AudioSource>()[0].Play();
            //Destroy(gameObject);
            Destroy(collision.gameObject);
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground") && this != null)
        {
            rotationAlright = true;
        }
    }

    /* private void OnTriggerEnter(Collider other)
     {
         if (other.gameObject.CompareTag("EnemyBullet") && this != null)
         {
             health--;
         }
     }*/
}

Yes, it is not recommended to use profiler during Editor running(even though I still do), as most of the CPU usage will be Editor related statistics and the profiler itself.

So if you’re sure that sounds are hurting severe performance, then something is wrong with their usage. Personally I would comment out all sounds, make sure everything else runs just fine without them(no duplicate calls, constant iterations, etc…). And then play with one new sound at a time.

I haven’t quite got far enough in any of my projects to even get to playing around with sound effects or music yet, so sorry I have no advice on Audio Manager or the best/performant ways of using it. But I know when that day comes, I’m gonna research long and hard on all of it’s functionalities, and of course best common practices on how to use it.

As I’ve found with any of my crashes, it’s because of a “run-away-for-loop” as I call it. Where something just keeps iterating over and over and never stops, and eventually is too much for Unity to handle. Normally a simple check, or “boolean = false” does the trick.

So one trick I did, was kinda set my games up like how old text games worked. I would have a print(or Debug.Log) function say what each thing is doing, and when it stops. When you watch all the info getting printed out, and see that a function you thought was only being called once, prints out 254 messages, lol, you know where the problem lies. :slight_smile:

A quick intro to optimization in Unity.

I strongly recommend some sleep if you’ve been at it for 120 hours! :smile:
Sorry, i just couldnt resist…

Other than what @wideeyenow_unity already said about the Profiler and the Editor, i would tackle this as two separate issues for now. You complain about framespikes / performance issues, as well as crashes.

The profiler should be able to tell you what’s going on in those frame spikes. Click on the spike of frame time and analyze what’s going on there. Have you verified that this is an editor related issue? Or are there also other things going on? Do the performance problems appear in a proper build?

Next, the crashes. Unless related to tons of memory allocation (which you should check), these are probably unrelated to your performance issues. Unity itself crashing is always a bit annoying to deal with. Creating an infinite loop or locking Unity up with other expensive tasks may cause it to freeze and eventually become unresponsive. There are some log files for these, but ive never tried actually reading them. I would only resort to that once the following doesnt help.

Some parts of your code are a bit weird, to very wrong:

  • this != null … why?

  • You set propeller volume to 0.5 each Update and then increment it by a miniscule amount when pressing W, which is overwritten to 0.5 next update. This is pointless. Other than that i cant really say too much about how to properly handle audio. This is not it tho :stuck_out_tongue:

  • I despise Coroutines. Exactly for reasons such as this. People never handle them correctly. Whenever someone posts code with a Coroutine on the forum, as a rule of thumb, it causes some kind of problem. Here, you dash. This sets ‘dashHappened’ to True. From this point in time onwards, for the next 5 seconds you start a Coroutine each frame to set dashHappened to False. With 100 FPS, this results in 500 Coroutines. A potential cause for your crash related issues, and certainly bad code. Just implement a small timer. You can just remember the time you dashed and then compare that value plus your cooldown to currenttime to decide whether you can dash again. Simple. Coroutines sound nice on paper, as they offer an easy way for seemingly async code execution… and then usually send the programmer to the forum for someone else to deal with it.

  • Find is notoriously expensive. You never want to use it in Update(). May not be related to your issues, just general feedback. Get the amount of rockets some other way than calling ‘GameObject.FindGameObjectsWithTag(“Rocket”)’ each single frame. Same for bullets… and all the other cases. Get rid of Find(). Always. Unless you write some exotic Editor tools yourself, you never need it.

  • All rigidbody (physics in general) related code belongs to FixedUpdate. You call move() in Update, which adds forces to the rigidbody. Likely not a huge issue, just letting you know. I didnt check where else you may violate this.

Misuse of Rigidbodies, use of Find() variations at all, and misuse of Coroutines are all common sources for issues.
Get rid of Find(), always. Get rid of Coroutines unless you know what you are doing. And usually when people use a Rigidbody they dont actually need a physics simulation, so for most games (may not apply to you), people want a CharacterController in the first place.

You should take a break :slight_smile: I don’t know about the sound issue but I can tell you one of major things that is (probably) affecting your ability to debug things. It is common enough but I recommend against putting all your game logic directly into the Update() method. It is not only (virtually) untestable it is unreusable.

Let me give you just one very small example and you can consider whether refactoring would get you anywhere. You can wrap the propellerSound stuff into a small unobtrusive class that can control the sound. All the parts needed, sound file, volume and loop “rules” would be in there. You can set it by passing in a Boolean value. So instead of relying on isHoldingW (this is what makes it untestable except when the game runs) generalize the solution. A test could then instantiate such an object and control all the aspects of the sound.

In any case… feel free to ignore the advice but complexity (if it hasn’t already become a problem) is going to become a problem so simplifying now will save you lots of time in the future.

        //MOST PROBLEMATIC PLACE
        if (health <= 0)
        {
            die();
        }
        //MOST PROBLEMATIC PLACE

die method is a coroutine but you called it like a normal function. You should use StartCoroutine method. This is the correct usage

StartCoroutine(die());

Thanks for the great advice! I will.

I tried it but no luck, game is still crashing after 20-30 second later.

I will try doing this, thanks!

Thanks! I will report back

THANK YOU! If I remember correctly you also helped me with my code some time ago. Thanks again! I will try every advice/solution you guys gave and I will report back.

I did everything you mentioned and game’s fps is between 100-299 and sometimes 1000 Thanks a lot! :slight_smile:

BUT, Unity still crashes after 20-30 second upon opening the game.

I wasn’t able to find any infinite loops. :frowning: Thanks for the advice tho!

I just decided to set the volume of the propeller at the start and nothing else. Thanks for the advice tho, I will think about this after this problem.

SOO the 100-290 frames were correct, ONLY IF I DIDN’T DO ANYTHING.

If I start flying my frame drops to 15-30 instantly. This problem makes me feel like a useless developer. Damn.

Thanks to AngryProgrammer, I think my fps drops were because of me instantiating so many bullets and rockets. I’m gonna try object pooling and I will report back.

Im glad we at least were able to improve the situation a bit so far. If you keep the profiler open, is there anything curious happening during the time until the game crashes? Like, does garbage keep accumulating, are there lagspikes, does the average frame take longer and longer to compute (and if so, why)? Anything? Does the game crash if you do nothing? Does it crash only or faster if you do certain actions? Are those in any way, shape or form reflected when you check the profiler?

If the above doesnt help, you could try to attach a proper debugger and step through the code slowly, to see where it crashes. Or you could try the likely tedious process of disabling certain parts of your game and checking if the issue persists (in theory you could always enable/disable half your games scripts, resulting in a sort-of binary search, but in practice this will be more tedious due to references and dependencies between components).

Edit: Oh and also, if after you went through the above and still need help, assuming you likely made major changes to your code when implementing some of my and the other suggestions, it would be good to post an up-to-date version. This is only relevant if you have a general idea of where the problem lies tho.

Thanks, I tried some stuff with it like firing bullets and stuff, but I checked my bullets weren’t the reason for Unity crashing. And my brain is kinda mushy right now, I don’t think I can change everything for that. Thanks tho!

Well, I will try recording and posting a video about it on youtube or something to show you guys. I don’t think I can explain the situation that well.

https://vimeo.com/853392907

And the code: (Profiller says the problem is mostly player so I’m posting the player’s code.)

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

public class PlayerController : MonoBehaviour
{
    public AudioSource propellerSound;
    public AudioSource gameMusic;

    //private GameManager gameManager;

    public Camera Camera;

    public GameObject plane;
    public GameObject propeller;
    [SerializeField] private Rigidbody rb;
    public GameObject algila;

    public Vector3 rotation;
    public Vector3 worldPos;
    public Vector3 offset;
    public Vector3 currentVelocity;

    public int health;

    public float horizontalInput;
    public float verticalInput;
    public float count = 0;
    [SerializeField] private float speed;
    public float currentSpeed;
    [SerializeField] private float turningSpeed = 0.5f;
    public float smoothTime = 0.25f;
    public float cameraSpeed;
    public float currentAmmo = 250;

    private bool isHoldingW = false;
    private bool isHoldingSpace = false;
    private bool isHoldingR = false;
    public bool rotationAlright = false;
    public bool movePlaneForward = false;
    public bool dashHappened = false;
    public bool canMove = true;
    public bool useAlternativeControls;
    public bool gameIsPlayable;

    public Material vinyet;

    public Transform[] spawnPlaces;

    public Transform[] rocketSpawnPlaces;

    public GameObject bullet1;
    public GameObject rocket1;

    public GameObject bulletParent;
    public GameObject rocketParent;

    public AudioSource mermiSes;

    public CheckFront checkFront;

    public float standartTimeRemaining = 2;
    public float timeRemaining;

    private int whichSideRocketSpawn = 1;

    private int bulletCount;
    private int rocketCount;

    public bool shouldSpawn;
    public bool shouldRocketSpawn;

    public AudioSource ucakDus;

    public float timeDashHappened;

    //private bool motorOverClocked = false;

    private void Start()
    {
        //gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();

        rb = GetComponent<Rigidbody>();

        ConfinedCursor();

        Camera = Camera.main;

        shouldSpawn = false;

        timeRemaining = standartTimeRemaining;

        checkFront = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<CheckFront>();

        propellerSound.volume = 0.5f;

        //LookAt();
    }


        horizontalInput = Input.GetAxis("HorizontalAD");
        verticalInput = Input.GetAxis("VerticalW");

        float rotateHorizontal = Input.GetAxis("Mouse X");
        float rotateVertical = Input.GetAxis("Mouse Y");

        float alternativeRotateHorizontal = Input.GetAxis("ArrowsLeftRight");
        float alternativeRotateVertical = Input.GetAxis("ArrowsUpDown");

        currentSpeed = Mathf.RoundToInt(rb.velocity.magnitude * 2.237f);

        propeller.transform.Rotate(0, 0, currentSpeed);

        if (Input.GetKeyDown(KeyCode.Q))
        {
            ConfinedCursor();
        }
        if (Input.GetKeyDown(KeyCode.E))
        {
            EscapedMouse();
        }

        if (Input.GetKeyDown(KeyCode.N))
        {
            useAlternativeControls = !useAlternativeControls;
        }

        if (gameIsPlayable)
        {
            transform.Rotate(rotation * turningSpeed);

            transform.Rotate(0, horizontalInput * turningSpeed, 0);

            isHoldingW = Input.GetKey(KeyCode.W);

            if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
            {
                if (!dashHappened)
                {
                    dash();
                    //Debug.Log("Dash happened!");
                }
            }

            if (dashHappened)
            {
                if ((timeDashHappened + 5) < Time.deltaTime)

                    dashHappened = false;
            }

            isHoldingSpace = Input.GetKey(KeyCode.Space);

            if (isHoldingSpace)
            {
                shouldSpawn = true;
            }
            else
            {
                shouldSpawn = false;
            }

            isHoldingR = Input.GetKeyDown(KeyCode.R);

            if (isHoldingR)
            {
                shouldRocketSpawn = true;
            }
            else
            {
                shouldRocketSpawn = false;
            }

            if (rotationAlright)
            {
                if (useAlternativeControls)
                {
                    rotation = new Vector3(alternativeRotateHorizontal * 2, 0.0f, alternativeRotateVertical * 2);
                }
                else
                    rotation = new Vector3(rotateHorizontal, 0.0f, rotateVertical);
            }
            else
            {
                rotation = Vector3.zero;
            }
        }

        Quaternion rotateCorrect = new Quaternion(this.transform.rotation.x, this.transform.rotation.y, this.transform.rotation.z, this.transform.rotation.w);
        Quaternion rotateCorrectRocket = new Quaternion(this.transform.rotation.x, this.transform.rotation.y - 93, this.transform.rotation.z, this.transform.rotation.w);

        bulletCount = bulletParent.transform.childCount;
        if (shouldSpawn && bulletCount < 50 && this.rotationAlright)
        {
            Instantiate(bullet1, spawnPlaces[0].transform.position, rotateCorrect, bulletParent.transform);
            Instantiate(bullet1, spawnPlaces[1].transform.position, rotateCorrect, bulletParent.transform);
            Instantiate(bullet1, spawnPlaces[2].transform.position, rotateCorrect, bulletParent.transform);
            Instantiate(bullet1, spawnPlaces[3].transform.position, rotateCorrect, bulletParent.transform);
        }

        rocketCount = rocketParent.transform.childCount;
        if (shouldRocketSpawn && rocketCount < 2 && this.rotationAlright)
        {
            if (whichSideRocketSpawn == 1)
            {
                Instantiate(rocket1, rocketSpawnPlaces[0].transform.position, rotateCorrectRocket, rocketParent.transform);

                whichSideRocketSpawn = 0;
            }
            else
            {
                Instantiate(rocket1, rocketSpawnPlaces[1].transform.position, rotateCorrectRocket, rocketParent.transform);

                whichSideRocketSpawn = 1;
            }
        }

        if (health <= 0)
        {
            StartCoroutine(die());
        }
    }

    private void FixedUpdate()
    {
        if (isHoldingW && currentSpeed < 200 && canMove)
        {
            move();
        }
    }

    private void move()
    {
        rb.AddRelativeForce(Vector3.left * speed * verticalInput);
        //speed += Time.deltaTime /2;
    }

    private void dash()
    {
        rb.AddRelativeForce(Vector3.left * currentSpeed / 1.5f * verticalInput, ForceMode.Impulse);
        dashHappened = true;
        timeDashHappened = Time.deltaTime;
    }

    private void ConfinedCursor()
    {
        Cursor.lockState = CursorLockMode.Confined;

        gameIsPlayable = true;

        Cursor.visible = false;

        movePlaneForward = false;
    }

    private void EscapedMouse()
    {
        Cursor.lockState = CursorLockMode.None;

        gameIsPlayable = false;

        Cursor.visible = true;
    }

    private IEnumerator die()
    {
        ucakDus.Play();

        if (!ucakDus.isPlaying)
        {
            yield return new WaitForSeconds(2);
            gameIsPlayable = false;

           
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground") && this != null)
        {
            rotationAlright = false;
        }
        else if (collision.gameObject.CompareTag("TESTPLACE") && this != null)
        {
            rotationAlright = true;
        }
        else if (collision.gameObject.CompareTag("EnemyRocket"))
        {
            health = health - 10;
            Destroy(collision.gameObject);
        }
        else if (collision.gameObject.CompareTag("EnemyPlaneRocket"))
        {
            health = health - 10;
            Destroy(collision.gameObject);
        }
        else if (collision.gameObject.CompareTag("EnemyBullet") && this != null)
        {
            health--;
        }
        else if (collision.gameObject.CompareTag("Enemy") && this != null)
        {
            gameObject.GetComponents<AudioSource>()[0].Play();
            //Destroy(gameObject);
            Destroy(collision.gameObject);
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground") && this != null)
        {
            rotationAlright = true;
        }
    }
}