Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved How can I optimize my code? THANKS EVERYONE

Discussion in 'Scripting' started by enesbagci2332, Aug 10, 2023.

  1. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    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:


    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. public class PlayerController : MonoBehaviour
    5. {
    6.     public AudioSource propellerSound;
    7.     public AudioSource gameMusic;
    8.     private GameManager gameManager;
    9.     public Camera Camera;
    10.     public GameObject plane;
    11.     public GameObject propeller;
    12.     [SerializeField] private Rigidbody rb;
    13.     public GameObject algila;  //ALGILA means DETECT
    14.  
    15.     public Vector3 rotation;
    16.     public Vector3 worldPos;
    17.     public Vector3 offset;
    18.     public Vector3 currentVelocity;
    19.  
    20.     public int health;
    21.  
    22.     public float horizontalInput;
    23.     public float verticalInput;
    24.     public float count = 0;
    25.     [SerializeField] private float speed;
    26.     public float currentSpeed;
    27.     [SerializeField] private float turningSpeed = 0.5f;
    28.     public float smoothTime = 0.25f;
    29.     public float cameraSpeed;
    30.     public float currentAmmo = 250;
    31.  
    32.     private bool isHoldingW = false;
    33.     private bool isHoldingSpace = false;
    34.     private bool isHoldingR = false;
    35.     public bool rotationAlright = false;
    36.     public bool movePlaneForward = false;
    37.     public bool dashHappened = false;
    38.     public bool canMove = true;
    39.     public bool useAlternativeControls;
    40.  
    41.     public Material vinyet;
    42.  
    43.     public GameObject spawnPlace1;
    44.     public GameObject spawnPlace2;
    45.     public GameObject spawnPlace3;
    46.     public GameObject spawnPlace4;
    47.  
    48.     public GameObject rocketSpawnPlace1;
    49.     public GameObject rocketSpawnPlace2;
    50.  
    51.     public GameObject bullet1;
    52.     public GameObject rocket1;
    53.  
    54.     public GameObject bulletParent;
    55.     public GameObject rocketParent;
    56.  
    57.     public AudioSource mermiSes;
    58.  
    59.     public CheckFront checkFront;
    60.  
    61.     public float standartTimeRemaining = 2;
    62.     public float timeRemaining;
    63.  
    64.     private int whichSideRocketSpawn = 1;
    65.  
    66.     private int bulletCount;
    67.     private int rocketCount;
    68.  
    69.     public bool shouldSpawn;
    70.     public bool shouldRocketSpawn;
    71.  
    72.     public AudioSource ucakDus;
    73.  
    74.     //private bool motorOverClocked = false;
    75.  
    76.     private void Start()
    77.     {
    78.         gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
    79.  
    80.         rb = GetComponent<Rigidbody>();
    81.  
    82.         ConfinedCursor();
    83.  
    84.         Camera = Camera.main;
    85.  
    86.         shouldSpawn = false;
    87.  
    88.         timeRemaining = standartTimeRemaining;
    89.  
    90.         checkFront = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<CheckFront>();
    91.  
    92.      
    93.     }
    94.  
    95.  
    96.     private void Update()
    97.     {
    98.  
    99.  
    100.        
    101.  
    102.         if (this != null)
    103.         {
    104.             //Debug.Log(GameObject.FindGameObjectWithTag("Bina").name);
    105.  
    106.             horizontalInput = Input.GetAxis("HorizontalAD");
    107.             verticalInput = Input.GetAxis("VerticalW");
    108.  
    109.             float rotateHorizontal = Input.GetAxis("Mouse X");
    110.             float rotateVertical = Input.GetAxis("Mouse Y");
    111.  
    112.             float alternativeRotateHorizontal = Input.GetAxis("ArrowsLeftRight");
    113.             float alternativeRotateVertical = Input.GetAxis("ArrowsUpDown");
    114.  
    115.             currentSpeed = Mathf.RoundToInt(rb.velocity.magnitude * 2.237f);
    116.  
    117.             propeller.transform.Rotate(0, 0, currentSpeed);
    118.  
    119.             propellerSound.volume = 0.5f;
    120.  
    121.             if (isHoldingW)
    122.             {
    123.                 propellerSound.volume += Time.deltaTime * 6;
    124.                 propellerSound.loop = true;
    125.             }
    126.             else
    127.             {
    128.                 propellerSound.volume -= Time.deltaTime;
    129.                 propellerSound.loop = false;
    130.             }
    131.  
    132.             if (Input.GetKeyDown(KeyCode.Q))
    133.             {
    134.                 ConfinedCursor();
    135.             }
    136.             if (Input.GetKeyDown(KeyCode.E))
    137.             {
    138.                 EscapedMouse();
    139.             }
    140.  
    141.             if (Input.GetKeyDown(KeyCode.N))
    142.             {
    143.                 useAlternativeControls = !useAlternativeControls;
    144.             }
    145.  
    146.             if (gameManager.gameIsPlayable)
    147.             {
    148.                 transform.Rotate(rotation * turningSpeed);
    149.  
    150.                 transform.Rotate(0, horizontalInput * turningSpeed, 0);
    151.  
    152.                 isHoldingW = Input.GetKey(KeyCode.W);
    153.  
    154.                 if (isHoldingW && currentSpeed < 200 && canMove)
    155.                 {
    156.                     move();
    157.                 }
    158.  
    159.                 if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
    160.                 {
    161.                     if (!dashHappened)
    162.                     {
    163.                         dash();
    164.                         //Debug.Log("Dash happened!");
    165.                     }
    166.                 }
    167.  
    168.                 if (dashHappened)
    169.                 {
    170.                     StartCoroutine(DashCooldown());
    171.                 }
    172.  
    173.                 isHoldingSpace = Input.GetKey(KeyCode.Space);
    174.  
    175.                 if (isHoldingSpace)
    176.                 {
    177.                     shouldSpawn = true;
    178.                 }
    179.                 else
    180.                 {
    181.                     shouldSpawn = false;
    182.                 }
    183.  
    184.                 isHoldingR = Input.GetKeyDown(KeyCode.R);
    185.  
    186.                 //This will detect clicking not holding, I will fix it's name later.
    187.                 if (isHoldingR)
    188.                 {
    189.                     shouldRocketSpawn = true;
    190.                 }
    191.                 else
    192.                 {
    193.                     shouldRocketSpawn = false;
    194.                 }
    195.  
    196.                 if (rotationAlright)
    197.                 {
    198.                     if (useAlternativeControls)
    199.                     {
    200.                         rotation = new Vector3(alternativeRotateHorizontal * 2, 0.0f, alternativeRotateVertical * 2);
    201.                     }
    202.                     else
    203.                         rotation = new Vector3(rotateHorizontal, 0.0f, rotateVertical);
    204.                 }
    205.                 else
    206.                 {
    207.                     rotation = Vector3.zero;
    208.                 }
    209.  
    210.              
    211.                
    212.             }
    213.         }
    214.         Quaternion rotateCorrect = new Quaternion(this.transform.rotation.x, this.transform.rotation.y, this.transform.rotation.z, this.transform.rotation.w);
    215.         Quaternion rotateCorrectRocket = new Quaternion(this.transform.rotation.x, this.transform.rotation.y - 93, this.transform.rotation.z, this.transform.rotation.w);
    216.  
    217.         /*if (algila.GetComponent<Algila>().timeHasSlowed)
    218.         {
    219.             mermiSes.pitch = 0.5f;
    220.         }
    221.         else
    222.         {
    223.             mermiSes.pitch = 1.0f;
    224.         }*/
    225.  
    226.         bulletCount = GameObject.FindGameObjectsWithTag("Bullet").Length;
    227.         if (shouldSpawn && bulletCount < 50 && this.rotationAlright)
    228.         {
    229.             Instantiate(bullet1, spawnPlace1.transform.position, rotateCorrect, bulletParent.transform);
    230.             Instantiate(bullet1, spawnPlace2.transform.position, rotateCorrect, bulletParent.transform);
    231.             Instantiate(bullet1, spawnPlace3.transform.position, rotateCorrect, bulletParent.transform);
    232.             Instantiate(bullet1, spawnPlace4.transform.position, rotateCorrect, bulletParent.transform);
    233.         }
    234.  
    235.         rocketCount = GameObject.FindGameObjectsWithTag("Rocket").Length;
    236.         if (shouldRocketSpawn && rocketCount < 2 && this.rotationAlright)
    237.         {
    238.             if (whichSideRocketSpawn == 1)
    239.             {
    240.                 Instantiate(rocket1, rocketSpawnPlace1.transform.position, rotateCorrectRocket, rocketParent.transform);
    241.  
    242.                 whichSideRocketSpawn = 0;
    243.             }
    244.             else
    245.             {
    246.                 Instantiate(rocket1, rocketSpawnPlace2.transform.position, rotateCorrectRocket, rocketParent.transform);
    247.  
    248.                 whichSideRocketSpawn = 1;
    249.             }
    250.         }
    251.  
    252.         if (movePlaneForward && this)
    253.         {
    254.             move();
    255.         }
    256.  
    257.         //MOST PROBLEMATIC PLACE
    258.  
    259.         if (health <= 0)
    260.         {
    261.             die();
    262.         }
    263.  
    264.         //MOST PROBLEMATIC PLACE
    265.     }
    266.  
    267.     private void move()
    268.     {
    269.         rb.AddRelativeForce(Vector3.left * speed * verticalInput);
    270.         //speed += Time.deltaTime /2;
    271.     }
    272.  
    273.     private void dash()
    274.     {
    275.         rb.AddRelativeForce(Vector3.left * currentSpeed / 1.5f * verticalInput, ForceMode.Impulse);
    276.         dashHappened = true;
    277.     }
    278.  
    279.     private void ConfinedCursor()
    280.     {
    281.         Cursor.lockState = CursorLockMode.Confined;
    282.  
    283.         gameManager.gameIsPlayable = true;
    284.  
    285.         Cursor.visible = false;
    286.  
    287.         movePlaneForward = false;
    288.     }
    289.  
    290.     private void EscapedMouse()
    291.     {
    292.         Cursor.lockState = CursorLockMode.None;
    293.  
    294.         gameManager.gameIsPlayable = false;
    295.  
    296.         Cursor.visible = true;
    297.     }
    298.  
    299.     private IEnumerator DashCooldown()
    300.     {
    301.         yield return new WaitForSeconds(5);
    302.  
    303.         //Debug.Log("Dash is ready!");
    304.  
    305.         dashHappened = false;
    306.     }
    307.  
    308. //MOST PROBLEMATIC PLACE
    309.  
    310.     private IEnumerator die()
    311.     {
    312.         ucakDus.Play();
    313.  
    314.         if (!ucakDus.isPlaying)
    315.         {
    316.             yield return new WaitForSeconds(2);
    317.             gameManager.gameIsPlayable = false;
    318.         }
    319.     }
    320.  
    321. //MOST PROBLEMATIC PLACE
    322.  
    323.     private void OnCollisionEnter(Collision collision)
    324.     {
    325.         if (collision.gameObject.CompareTag("Ground") && this != null)
    326.         {
    327.             rotationAlright = false;
    328.         }
    329.         else if (collision.gameObject.CompareTag("TESTPLACE") && this != null)
    330.         {
    331.             rotationAlright = true;
    332.         }
    333.         else if (collision.gameObject.CompareTag("EnemyRocket"))
    334.         {
    335.             health = health - 10;
    336.             Destroy(collision.gameObject);
    337.         }
    338.         else if (collision.gameObject.CompareTag("EnemyPlaneRocket"))
    339.         {
    340.             health = health - 10;
    341.             Destroy(collision.gameObject);
    342.         }
    343.         else if (collision.gameObject.CompareTag("EnemyBullet") && this != null)
    344.         {
    345.             health--;
    346.         }
    347.         else if (collision.gameObject.CompareTag("Enemy") && this != null)
    348.         {
    349.             gameObject.GetComponents<AudioSource>()[0].Play();
    350.             //Destroy(gameObject);
    351.             Destroy(collision.gameObject);
    352.         }
    353.     }
    354.  
    355.     private void OnCollisionExit(Collision collision)
    356.     {
    357.         if (collision.gameObject.CompareTag("Ground") && this != null)
    358.         {
    359.             rotationAlright = true;
    360.         }
    361.     }
    362.  
    363.     /* private void OnTriggerEnter(Collider other)
    364.      {
    365.          if (other.gameObject.CompareTag("EnemyBullet") && this != null)
    366.          {
    367.              health--;
    368.          }
    369.      }*/
    370. }
     
  2. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    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. :)
     
    enesbagci2332 and Yoreki like this.
  3. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    431
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    I strongly recommend some sleep if you've been at it for 120 hours! :D
    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 :p
    • 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.
     
    Last edited: Aug 10, 2023
  5. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    521
    You should take a break :) 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.
     
    Bunny83 and enesbagci2332 like this.
  6. icauroboros

    icauroboros

    Joined:
    Apr 30, 2021
    Posts:
    99
    Code (CSharp):
    1.  
    2.         //MOST PROBLEMATIC PLACE
    3.         if (health <= 0)
    4.         {
    5.             die();
    6.         }
    7.         //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
    Code (CSharp):
    1. StartCoroutine(die());
     
    enesbagci2332 likes this.
  7. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    Thanks for the great advice! I will.
     
  8. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

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

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I will try doing this, thanks!
     
  10. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
  11. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82


    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.
     
  12. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82



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



    BUT, Unity still crashes after 20-30 second upon opening the game.
     
    Yoreki likes this.
  13. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I wasn't able to find any infinite loops. :( Thanks for the advice tho!
     
  14. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    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.
     
  15. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    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.
     
  16. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
  17. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    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.
     
  18. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    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!
     
  19. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    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.
     
  20. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82



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



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     public AudioSource propellerSound;
    8.     public AudioSource gameMusic;
    9.  
    10.     //private GameManager gameManager;
    11.  
    12.     public Camera Camera;
    13.  
    14.     public GameObject plane;
    15.     public GameObject propeller;
    16.     [SerializeField] private Rigidbody rb;
    17.     public GameObject algila;
    18.  
    19.     public Vector3 rotation;
    20.     public Vector3 worldPos;
    21.     public Vector3 offset;
    22.     public Vector3 currentVelocity;
    23.  
    24.     public int health;
    25.  
    26.     public float horizontalInput;
    27.     public float verticalInput;
    28.     public float count = 0;
    29.     [SerializeField] private float speed;
    30.     public float currentSpeed;
    31.     [SerializeField] private float turningSpeed = 0.5f;
    32.     public float smoothTime = 0.25f;
    33.     public float cameraSpeed;
    34.     public float currentAmmo = 250;
    35.  
    36.     private bool isHoldingW = false;
    37.     private bool isHoldingSpace = false;
    38.     private bool isHoldingR = false;
    39.     public bool rotationAlright = false;
    40.     public bool movePlaneForward = false;
    41.     public bool dashHappened = false;
    42.     public bool canMove = true;
    43.     public bool useAlternativeControls;
    44.     public bool gameIsPlayable;
    45.  
    46.     public Material vinyet;
    47.  
    48.     public Transform[] spawnPlaces;
    49.  
    50.     public Transform[] rocketSpawnPlaces;
    51.  
    52.     public GameObject bullet1;
    53.     public GameObject rocket1;
    54.  
    55.     public GameObject bulletParent;
    56.     public GameObject rocketParent;
    57.  
    58.     public AudioSource mermiSes;
    59.  
    60.     public CheckFront checkFront;
    61.  
    62.     public float standartTimeRemaining = 2;
    63.     public float timeRemaining;
    64.  
    65.     private int whichSideRocketSpawn = 1;
    66.  
    67.     private int bulletCount;
    68.     private int rocketCount;
    69.  
    70.     public bool shouldSpawn;
    71.     public bool shouldRocketSpawn;
    72.  
    73.     public AudioSource ucakDus;
    74.  
    75.     public float timeDashHappened;
    76.  
    77.     //private bool motorOverClocked = false;
    78.  
    79.     private void Start()
    80.     {
    81.         //gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
    82.  
    83.         rb = GetComponent<Rigidbody>();
    84.  
    85.         ConfinedCursor();
    86.  
    87.         Camera = Camera.main;
    88.  
    89.         shouldSpawn = false;
    90.  
    91.         timeRemaining = standartTimeRemaining;
    92.  
    93.         checkFront = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<CheckFront>();
    94.  
    95.         propellerSound.volume = 0.5f;
    96.  
    97.         //LookAt();
    98.     }
    99.  
    100.  
    101.         horizontalInput = Input.GetAxis("HorizontalAD");
    102.         verticalInput = Input.GetAxis("VerticalW");
    103.  
    104.         float rotateHorizontal = Input.GetAxis("Mouse X");
    105.         float rotateVertical = Input.GetAxis("Mouse Y");
    106.  
    107.         float alternativeRotateHorizontal = Input.GetAxis("ArrowsLeftRight");
    108.         float alternativeRotateVertical = Input.GetAxis("ArrowsUpDown");
    109.  
    110.         currentSpeed = Mathf.RoundToInt(rb.velocity.magnitude * 2.237f);
    111.  
    112.         propeller.transform.Rotate(0, 0, currentSpeed);
    113.  
    114.         if (Input.GetKeyDown(KeyCode.Q))
    115.         {
    116.             ConfinedCursor();
    117.         }
    118.         if (Input.GetKeyDown(KeyCode.E))
    119.         {
    120.             EscapedMouse();
    121.         }
    122.  
    123.         if (Input.GetKeyDown(KeyCode.N))
    124.         {
    125.             useAlternativeControls = !useAlternativeControls;
    126.         }
    127.  
    128.         if (gameIsPlayable)
    129.         {
    130.             transform.Rotate(rotation * turningSpeed);
    131.  
    132.             transform.Rotate(0, horizontalInput * turningSpeed, 0);
    133.  
    134.             isHoldingW = Input.GetKey(KeyCode.W);
    135.  
    136.             if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
    137.             {
    138.                 if (!dashHappened)
    139.                 {
    140.                     dash();
    141.                     //Debug.Log("Dash happened!");
    142.                 }
    143.             }
    144.  
    145.             if (dashHappened)
    146.             {
    147.                 if ((timeDashHappened + 5) < Time.deltaTime)
    148.  
    149.                     dashHappened = false;
    150.             }
    151.  
    152.             isHoldingSpace = Input.GetKey(KeyCode.Space);
    153.  
    154.             if (isHoldingSpace)
    155.             {
    156.                 shouldSpawn = true;
    157.             }
    158.             else
    159.             {
    160.                 shouldSpawn = false;
    161.             }
    162.  
    163.             isHoldingR = Input.GetKeyDown(KeyCode.R);
    164.  
    165.             if (isHoldingR)
    166.             {
    167.                 shouldRocketSpawn = true;
    168.             }
    169.             else
    170.             {
    171.                 shouldRocketSpawn = false;
    172.             }
    173.  
    174.             if (rotationAlright)
    175.             {
    176.                 if (useAlternativeControls)
    177.                 {
    178.                     rotation = new Vector3(alternativeRotateHorizontal * 2, 0.0f, alternativeRotateVertical * 2);
    179.                 }
    180.                 else
    181.                     rotation = new Vector3(rotateHorizontal, 0.0f, rotateVertical);
    182.             }
    183.             else
    184.             {
    185.                 rotation = Vector3.zero;
    186.             }
    187.         }
    188.  
    189.         Quaternion rotateCorrect = new Quaternion(this.transform.rotation.x, this.transform.rotation.y, this.transform.rotation.z, this.transform.rotation.w);
    190.         Quaternion rotateCorrectRocket = new Quaternion(this.transform.rotation.x, this.transform.rotation.y - 93, this.transform.rotation.z, this.transform.rotation.w);
    191.  
    192.         bulletCount = bulletParent.transform.childCount;
    193.         if (shouldSpawn && bulletCount < 50 && this.rotationAlright)
    194.         {
    195.             Instantiate(bullet1, spawnPlaces[0].transform.position, rotateCorrect, bulletParent.transform);
    196.             Instantiate(bullet1, spawnPlaces[1].transform.position, rotateCorrect, bulletParent.transform);
    197.             Instantiate(bullet1, spawnPlaces[2].transform.position, rotateCorrect, bulletParent.transform);
    198.             Instantiate(bullet1, spawnPlaces[3].transform.position, rotateCorrect, bulletParent.transform);
    199.         }
    200.  
    201.         rocketCount = rocketParent.transform.childCount;
    202.         if (shouldRocketSpawn && rocketCount < 2 && this.rotationAlright)
    203.         {
    204.             if (whichSideRocketSpawn == 1)
    205.             {
    206.                 Instantiate(rocket1, rocketSpawnPlaces[0].transform.position, rotateCorrectRocket, rocketParent.transform);
    207.  
    208.                 whichSideRocketSpawn = 0;
    209.             }
    210.             else
    211.             {
    212.                 Instantiate(rocket1, rocketSpawnPlaces[1].transform.position, rotateCorrectRocket, rocketParent.transform);
    213.  
    214.                 whichSideRocketSpawn = 1;
    215.             }
    216.         }
    217.  
    218.         if (health <= 0)
    219.         {
    220.             StartCoroutine(die());
    221.         }
    222.     }
    223.  
    224.     private void FixedUpdate()
    225.     {
    226.         if (isHoldingW && currentSpeed < 200 && canMove)
    227.         {
    228.             move();
    229.         }
    230.     }
    231.  
    232.     private void move()
    233.     {
    234.         rb.AddRelativeForce(Vector3.left * speed * verticalInput);
    235.         //speed += Time.deltaTime /2;
    236.     }
    237.  
    238.     private void dash()
    239.     {
    240.         rb.AddRelativeForce(Vector3.left * currentSpeed / 1.5f * verticalInput, ForceMode.Impulse);
    241.         dashHappened = true;
    242.         timeDashHappened = Time.deltaTime;
    243.     }
    244.  
    245.     private void ConfinedCursor()
    246.     {
    247.         Cursor.lockState = CursorLockMode.Confined;
    248.  
    249.         gameIsPlayable = true;
    250.  
    251.         Cursor.visible = false;
    252.  
    253.         movePlaneForward = false;
    254.     }
    255.  
    256.     private void EscapedMouse()
    257.     {
    258.         Cursor.lockState = CursorLockMode.None;
    259.  
    260.         gameIsPlayable = false;
    261.  
    262.         Cursor.visible = true;
    263.     }
    264.  
    265.     private IEnumerator die()
    266.     {
    267.         ucakDus.Play();
    268.  
    269.         if (!ucakDus.isPlaying)
    270.         {
    271.             yield return new WaitForSeconds(2);
    272.             gameIsPlayable = false;
    273.  
    274.            
    275.         }
    276.     }
    277.  
    278.     private void OnCollisionEnter(Collision collision)
    279.     {
    280.         if (collision.gameObject.CompareTag("Ground") && this != null)
    281.         {
    282.             rotationAlright = false;
    283.         }
    284.         else if (collision.gameObject.CompareTag("TESTPLACE") && this != null)
    285.         {
    286.             rotationAlright = true;
    287.         }
    288.         else if (collision.gameObject.CompareTag("EnemyRocket"))
    289.         {
    290.             health = health - 10;
    291.             Destroy(collision.gameObject);
    292.         }
    293.         else if (collision.gameObject.CompareTag("EnemyPlaneRocket"))
    294.         {
    295.             health = health - 10;
    296.             Destroy(collision.gameObject);
    297.         }
    298.         else if (collision.gameObject.CompareTag("EnemyBullet") && this != null)
    299.         {
    300.             health--;
    301.         }
    302.         else if (collision.gameObject.CompareTag("Enemy") && this != null)
    303.         {
    304.             gameObject.GetComponents<AudioSource>()[0].Play();
    305.             //Destroy(gameObject);
    306.             Destroy(collision.gameObject);
    307.         }
    308.     }
    309.  
    310.     private void OnCollisionExit(Collision collision)
    311.     {
    312.         if (collision.gameObject.CompareTag("Ground") && this != null)
    313.         {
    314.             rotationAlright = true;
    315.         }
    316.     }
    317. }
     
  21. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    EDIT: Also the enemy is making those attacking noises, opening or closing the enemy doesn't change anything.
     
  22. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Yeah I figured you wouldn't be able to profile it, because the crash would just freeze up everything. And I'm pretty sure profiler would crash with Unity, although I think you can make a stand-alone profiler, that will still stay even if Unity crashed, but don't quote me on that.

    Unity, best I can tell can handle 10,000 GetComponent() type calls without flinching(too much, lol).

    So you must have something calling like crazy, each frame, if not more(compounding each new frame).

    As Yoreki stated, it's more than likely a coroutine setup that is just compounding on itself.

    I'll try to put my thinking cap on and study your code. But I never accurately think like the compiler does, lol, so I always miss stuff.. But I'm not afraid to try! :cool:
     
    enesbagci2332 likes this.
  23. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    Thanks! You guys are helping me so much, even though the problem isn't solved right now thank you, everyone.
     
  24. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    You seem to be missing the Update() right around line 100, but I'll assume that was just a copy/paste mistake.


    This makes no sense as the Unity axis are "Horizontal" and "Vertical", not sure why other letters are on the end of them.


    Not sure why you have 2 rotate calls here, but should just be set as one.


    There is nothing stopping this coroutine from constantly thinking. Not fully sure if your health is even lowering, to run this yet, but this will be a problem for sure. You only want a coroutine to run once, so I suggest a bool added to this, or some other form of check.

    Other than those things, I'm not really seeing much wrong. But in that clip, I definitely hear the enemies going crazy, so now I'm wondering if it isn't them that's also contributing, or fully causing the crash?
     
    Yoreki likes this.
  25. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Also you don't have "Live" data turned on, so you can't see what processes are doing. Click that on, which should show in the bottom window of all the data, "Player loop" "Editor loop" etc...

    You specifically want to be looking in player loop, and see where it shows functions you have named, because sometimes there are 2 different ones. But hit the pause button to stop it right (well)before you know it's going to crash, and then look at the frame data to see what's being called and how much time it needs to think(milliseconds).

    To be fair, if something is using up more than 1 full millisecond of CPU time, judging by how much should not be running in your game at this moment, then that is definitely your problem.

    Or you could probably also see hundreds or thousands of Coroutine calls, but each hierarchy should group up how much of each child is using. So should be pretty easy to follow the big numbers(not the numbers in editor loop!).
     
  26. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    These are not default axis names, but Unity does allow to create custom virtual axis. I assume OP did.

    You are right on the die() Coroutine however.
    This one will cause problems for the same reasons the dash cooldown one did.

    @enesbagci2332 did you try turning off enemies? Does this have any effect on the crashing? Try incrementally disabling parts of your game until the crash does not appear anymore. Then try enabling as much as possible again until you pinpointed which causes the issues you experience. Then we can have a look at those components as well!
     
  27. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I deactivated enemies but no change still crashes and the profiler also says the player loop uses so much CPU.

    Other than that like @Yoreki said those axis are custom virtual axis.

    I'm going to try deactivating both the dash and die systems.
     
  28. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    YES, THE DASH AND DIE SYSTEMS WERE BROKEN, BECAUSE I WROTE THE DASH SYSTEM AT LIKE THE START OF THE GAME I DIDN'T TOUGHT ANYTHING MUCH ABOUT IT. BUT THE DASH SYSTEM WAS THE BROKEN THING.


    THANK YOU, EVERYONE.

    I'm gonna upload a video showing that it's solved. Again thanks, everyone!







    LETSSSSSSSSSSS GOOOOOOOOOOOOOOOOOOOOOOOOO
     
  29. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I wasn't waiting for it to actually stay at 1000 fps so I was surprised. :D
     
  30. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    UPDATE: After this post

    I added enemies back and enemies instantly crashed the game. My fps was bad but I fixed it. Game runs on 60 fps on it's worst. BUT STILL I DON'T KNOW WHY. I TRIED USING A BUILD VERSION OF MY GAME. GAME WAS GOING WITH 60 fps no problem. BUT STILL CRASHED.



    WHYYYYYYYYYYYYYYYYYYYYYYYYY?


    Is there something in the game making like a sin or something; "if you do this your game will crash." WHAT DID I DO?! WHY MY GAME CRASHES:


    I'm sorry for taking your time lads. But if you have any idea about this crash problem. Please help my game.
     
  31. CodeRonnie

    CodeRonnie

    Joined:
    Oct 2, 2015
    Posts:
    280
    Running completely out of memory, using up all of the available RAM, will crash your game. Creating a stack overflow where your methods are infinitely looping back in on themselves in a single frame will also crash your game.
     
  32. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    521
    It crashes because you are not sure what it is doing at any particular point in time. Software development isn't a guessing game. It is an orderly set of steps that the computer follows. You've told it to crash somewhere, somehow. Inadvertently of course but who else could have done it, it is your code.

    Stop and fix what you have so it makes sense. Here are a few things you can implement quite easily.

    Code (CSharp):
    1. if (isHoldingSpace)
    2. {
    3.     shouldSpawn = true;
    4. }
    5. else
    6. {
    7.     shouldSpawn = false;
    8. }
    9.  
    shouldSpawn is obviously equal to isHoldingSpace

    shouldSpawn = isHoldingSpace;

    Code (CSharp):
    1. if (isHoldingR)
    2. {
    3.     shouldRocketSpawn = true;
    4. }
    5. else
    6. {
    7.     shouldRocketSpawn = false;
    8. }
    9.  
    shouldRocketSpawn is equal to isHoldingR so same basic solution just assign the value to shouldRocketSpawn.

    And notice that you have "shouldSpawn" and "shouldRocketSpawn" the first one is a bullet spawn right so it should be shouldBulletSpawn. Consistency is good.

    Code (CSharp):
    1. bulletCount = bulletParent.transform.childCount;
    2.  
    3. if (shouldSpawn && bulletCount < 50 && this.rotationAlright)
    4. {
    5.     Instantiate(bullet1, spawnPlaces[0].transform.position, rotateCorrect, bulletParent.transform);
    6.     Instantiate(bullet1, spawnPlaces[1].transform.position, rotateCorrect, bulletParent.transform);
    7.     Instantiate(bullet1, spawnPlaces[2].transform.position, rotateCorrect, bulletParent.transform);
    8.     Instantiate(bullet1, spawnPlaces[3].transform.position, rotateCorrect, bulletParent.transform);
    9. }
    10.  
    I would probably add a private method named GetBulletCount you can call it from more than one spot, test it, log the value, etc. I don't know if you need the bulletCount if shouldSpawn is false or this.rotationAlright is false so perhaps separate those tests. The only difference in the 4 instantiate lines is the array index Surely that can be done in a loop.

    Code (CSharp):
    1. if (whichSideRocketSpawn == 1)
    2. {
    3.     Instantiate(rocket1, rocketSpawnPlaces[0].transform.position, rotateCorrectRocket, rocketParent.transform);
    4.  
    5.     whichSideRocketSpawn = 0;
    6. }
    7. else
    8. {
    9.     Instantiate(rocket1, rocketSpawnPlaces[1].transform.position, rotateCorrectRocket, rocketParent.transform);
    10.  
    11.     whichSideRocketSpawn = 1;
    12. }
    13.  
    Similarly you have set up an integer to determine which side to spawn but have arbitrarily decided that 0 and 1 won't correspond to the array element (which I assume it could). So make whichSideRocketSpawn the index and remove the nearly duplicate lines here as well.

    Understand what the code does, make it testable, make it easy to stub out things you don't need while testing or to refactor something without committing to the change until you know it works.

    Add logging.
     
  33. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    If the crashes only reappeared once you reenabled enemies at least you know where to look. It's some mechanic involving enemies. This means either the scripts running on the enemies themselves, or some other scripts that only do something if enemies exist. Likely the former.

    We havent yet seen the code of your enemy scripts, but we did talk a bit about what could crash Unity. Check for infinite loops of some sort, or spamm-creating way too many objects by doing something each frame, instead of once. Based on the issues so far, if you use coroutines in your enemy scripts, that would be a nice place to start looking into ;)
     
    enesbagci2332 likes this.
  34. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    You more than likely have another compounding coroutine within the enemy script. Best suggestion? Is don't use coroutines! :)
     
    enesbagci2332 likes this.
  35. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I'm gonna start hating on coroutines
     
    wideeyenow_unity and Yoreki like this.
  36. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I have changed my code based on your suggestions.
     
  37. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    This is the player's code, I hope I didn't do any mistakes.

    PLAYER'S CODE:


    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Rendering;
    3.  
    4. public class PlayerController : MonoBehaviour
    5. {
    6.     public AudioSource propellerSound;
    7.     public AudioSource gameMusic;
    8.  
    9.     //private GameManager gameManager;
    10.  
    11.     public Camera camera1;
    12.     public FreeCamera freeCamera;
    13.  
    14.     public GameObject plane;
    15.     public GameObject propeller;
    16.     [SerializeField] private Rigidbody rb;
    17.     public GameObject algila;
    18.  
    19.     public Vector3 rotation;
    20.     public Vector3 worldPos;
    21.     public Vector3 offset;
    22.     public Vector3 currentVelocity;
    23.  
    24.     public int health;
    25.  
    26.     public float horizontalInput;
    27.     public float verticalInput;
    28.     public float count = 0;
    29.     [SerializeField] private float speed;
    30.     public float currentSpeed;
    31.     [SerializeField] private float turningSpeed = 0.5f;
    32.     public float smoothTime = 0.25f;
    33.     public float cameraSpeed;
    34.     public float currentAmmo = 250;
    35.  
    36.     private bool isHoldingW = false;
    37.     private bool isHoldingSpace = false;
    38.     private bool isHoldingR = false;
    39.     public bool rotationAlright = false;
    40.     public bool movePlaneForward = false;
    41.     public bool dashHappened = false;
    42.     public bool canMove = true;
    43.     public bool useAlternativeControls;
    44.     public bool gameIsPlayable;
    45.  
    46.     public Material vinyet;
    47.  
    48.     public Transform[] spawnPlaces;
    49.  
    50.     public Transform[] rocketSpawnPlaces;
    51.  
    52.     public GameObject bullet1;
    53.     public GameObject rocket1;
    54.  
    55.     public GameObject bulletParent;
    56.     public GameObject rocketParent;
    57.  
    58.     public AudioSource mermiSes;
    59.  
    60.     public CheckFront checkFront;
    61.  
    62.     public float standartTimeRemaining = 2;
    63.     public float timeRemaining;
    64.  
    65.     private int whichSideRocketSpawn = 1;
    66.  
    67.     private int bulletCount;
    68.     private int rocketCount;
    69.  
    70.     public bool shouldSpawn;
    71.     public bool shouldRocketSpawn;
    72.  
    73.     public AudioSource ucakDus;
    74.  
    75.     public float timeDashHappened;
    76.  
    77.     //private bool motorOverClocked = false;
    78.  
    79.     private void Start()
    80.     {
    81.         //gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
    82.  
    83.         rb = GetComponent<Rigidbody>();
    84.  
    85.         ConfinedCursor();
    86.  
    87.         camera1 = Camera.main;
    88.  
    89.         shouldSpawn = false;
    90.  
    91.         timeRemaining = standartTimeRemaining;
    92.  
    93.         checkFront = GameObject.FindGameObjectWithTag("Player").GetComponentInChildren<CheckFront>();
    94.  
    95.         propellerSound.volume = 0.5f;
    96.  
    97.         //LookAt();
    98.     }
    99.  
    100.     private static bool bruh = false;
    101.  
    102.     private void Update()
    103.     {
    104.         //Get every single audio sources in the scene.
    105.         //sources = GameObject.FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
    106.  
    107.         //Debug.Log(GameObject.FindGameObjectWithTag("Bina").name);
    108.  
    109.         horizontalInput = Input.GetAxis("HorizontalAD");
    110.         verticalInput = Input.GetAxis("VerticalW");
    111.  
    112.         float rotateHorizontal = Input.GetAxis("Mouse X");
    113.         float rotateVertical = Input.GetAxis("Mouse Y");
    114.  
    115.         float alternativeRotateHorizontal = Input.GetAxis("ArrowsLeftRight");
    116.         float alternativeRotateVertical = Input.GetAxis("ArrowsUpDown");
    117.  
    118.         currentSpeed = Mathf.RoundToInt(rb.velocity.magnitude * 2.237f);
    119.  
    120.         propeller.transform.Rotate(0, 0, currentSpeed);
    121.  
    122.         //LookAt();
    123.  
    124.         if (Input.GetKeyDown(KeyCode.Q))
    125.         {
    126.             ConfinedCursor();
    127.         }
    128.         if (Input.GetKeyDown(KeyCode.E))
    129.         {
    130.             EscapedMouse();
    131.         }
    132.  
    133.         if (Input.GetKeyDown(KeyCode.N))
    134.         {
    135.             useAlternativeControls = !useAlternativeControls;
    136.         }
    137.  
    138.         if (gameIsPlayable)
    139.         {
    140.             transform.Rotate(rotation * turningSpeed);
    141.  
    142.             transform.Rotate(0, horizontalInput * turningSpeed, 0);
    143.  
    144.             isHoldingW = Input.GetKey(KeyCode.W);
    145.  
    146.             /*if (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
    147.             {
    148.                 if (!dashHappened)
    149.                 {
    150.                     dash();
    151.                     //Debug.Log("Dash happened!");
    152.                 }
    153.             }*/
    154.  
    155.             if (dashHappened)
    156.             {
    157.                 if ((timeDashHappened + 5) < Time.deltaTime)
    158.  
    159.                     dashHappened = false;
    160.             }
    161.  
    162.             isHoldingSpace = Input.GetKey(KeyCode.Space);
    163.  
    164.             if (isHoldingSpace)
    165.             {
    166.                 shouldSpawn = isHoldingSpace;
    167.             }
    168.             else
    169.             {
    170.                 shouldSpawn = isHoldingSpace;
    171.             }
    172.  
    173.             isHoldingR = Input.GetKeyDown(KeyCode.R);
    174.  
    175.             if (isHoldingR)
    176.             {
    177.                 shouldRocketSpawn = isHoldingR;
    178.             }
    179.             else
    180.             {
    181.                 shouldRocketSpawn = isHoldingR;
    182.             }
    183.  
    184.             if (rotationAlright)
    185.             {
    186.                 if (useAlternativeControls)
    187.                 {
    188.                     rotation = new Vector3(alternativeRotateHorizontal * 2, 0.0f, alternativeRotateVertical * 2);
    189.                 }
    190.                 else
    191.                     rotation = new Vector3(rotateHorizontal, 0.0f, rotateVertical);
    192.             }
    193.             else
    194.             {
    195.                 rotation = Vector3.zero;
    196.             }
    197.         }
    198.  
    199.         Quaternion rotateCorrect = new Quaternion(transform.rotation.x, transform.rotation.y, transform.rotation.z, transform.rotation.w);
    200.         Quaternion rotateCorrectRocket = new Quaternion(transform.rotation.x, transform.rotation.y - 93, transform.rotation.z, transform.rotation.w);
    201.  
    202.         bulletCount = bulletParent.transform.childCount;
    203.         if (shouldSpawn && bulletCount < 50 && rotationAlright)
    204.         {
    205.             for (int i = 0; i < 4; i++)
    206.             {
    207.                 Instantiate(bullet1, spawnPlaces[i].transform.position, rotateCorrect, bulletParent.transform);
    208.             }
    209.         }
    210.  
    211.         rocketCount = rocketParent.transform.childCount;
    212.         if (shouldRocketSpawn && rocketCount < 2 && rotationAlright)
    213.         {
    214.             for (int i = 0; i < 1; i++)
    215.             {
    216.                 Instantiate(rocket1, rocketSpawnPlaces[Random.Range(0, 2)].transform.position, rotateCorrectRocket, rocketParent.transform);
    217.             }
    218.         }
    219.  
    220.         if (health <= 0 && bruh == false)
    221.         {
    222.             die();
    223.         }
    224.     }
    225.  
    226.     private void FixedUpdate()
    227.     {
    228.         if (isHoldingW && currentSpeed < 200 && canMove)
    229.         {
    230.             move();
    231.         }
    232.     }
    233.  
    234.     private void move()
    235.     {
    236.         rb.AddRelativeForce(Vector3.left * speed * verticalInput);
    237.         //speed += Time.deltaTime /2;
    238.     }
    239.  
    240.     /* private void dash()
    241.      {
    242.          rb.AddRelativeForce(Vector3.left * currentSpeed / 1.5f * verticalInput, ForceMode.Impulse);
    243.          dashHappened = true;
    244.          timeDashHappened = Time.deltaTime;
    245.      }*/
    246.  
    247.     private void ConfinedCursor()
    248.     {
    249.         Cursor.lockState = CursorLockMode.Confined;
    250.  
    251.         gameIsPlayable = true;
    252.  
    253.         Cursor.visible = false;
    254.  
    255.         movePlaneForward = false;
    256.     }
    257.  
    258.     private void EscapedMouse()
    259.     {
    260.         Cursor.lockState = CursorLockMode.None;
    261.  
    262.         gameIsPlayable = false;
    263.  
    264.         Cursor.visible = true;
    265.     }
    266.  
    267.     private void die()
    268.     {
    269.         bruh = true;
    270.         ucakDus.Play();
    271.  
    272.         gameIsPlayable = false;
    273.  
    274.         Debug.Log("DIE player");
    275.     }
    276.  
    277.     private void OnCollisionEnter(Collision collision)
    278.     {
    279.         if (collision.gameObject.CompareTag("Ground") && this != null)
    280.         {
    281.             rotationAlright = false;
    282.         }
    283.         else if (collision.gameObject.CompareTag("TESTPLACE") && this != null)
    284.         {
    285.             rotationAlright = true;
    286.         }
    287.         else if (collision.gameObject.CompareTag("EnemyRocket"))
    288.         {
    289.             health = health - 10;
    290.             Destroy(collision.gameObject);
    291.         }
    292.         else if (collision.gameObject.CompareTag("EnemyPlaneRocket"))
    293.         {
    294.             health = health - 10;
    295.             Destroy(collision.gameObject);
    296.         }
    297.         else if (collision.gameObject.CompareTag("EnemyBullet") && this != null)
    298.         {
    299.             health--;
    300.         }
    301.         else if (collision.gameObject.CompareTag("Enemy") && this != null)
    302.         {
    303.             gameObject.GetComponents<AudioSource>()[0].Play();
    304.             //Destroy(gameObject);
    305.             Destroy(collision.gameObject);
    306.         }
    307.     }
    308.  
    309.     private void OnCollisionExit(Collision collision)
    310.     {
    311.         if (collision.gameObject.CompareTag("Ground") && this != null)
    312.         {
    313.             rotationAlright = true;
    314.         }
    315.     }
    316. }
    317.  
     
  38. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I'm making some changes on my enemy script based on the advice I got from you guys. I will share it after that
     
  39. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    ENEMY SCRIPT:


    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class EnemyController : MonoBehaviour
    4.  
    5. {
    6.     public PlayerController playerController;
    7.  
    8.     [SerializeField] private Rigidbody rb;
    9.  
    10.     public Vector3 rotation;
    11.     public Vector3 currentVelocity;
    12.     public Vector3 direction;
    13.  
    14.     public GameObject propeller;
    15.     public GameObject player;
    16.     public GameObject playerPropeller;
    17.  
    18.     public bool playerLocked;
    19.  
    20.     [SerializeField] private float speed;
    21.  
    22.     public bool chaseState;
    23.  
    24.     public bool anEnemyAlreadyFollows;
    25.  
    26.     public float smoothTime = 0.25f;
    27.  
    28.     public int enemyAircraftHealth;
    29.  
    30.     public Transform[] spawnPlaces;
    31.  
    32.     public Transform[] rocketSpawnPlaces;
    33.  
    34.     //private bool canEnemySpawn = true;
    35.  
    36.     public GameObject bullet1;
    37.     public GameObject rocket1;
    38.  
    39.     public GameObject bulletParent;
    40.     public GameObject rocketParent;
    41.  
    42.     private int bulletCount;
    43.     private int rocketCount;
    44.  
    45.     public bool shouldBulletSpawn;
    46.     public bool shouldRocketSpawn;
    47.  
    48.     public Quaternion rotateCorrect;
    49.  
    50.     public AudioSource ucakDus;
    51.  
    52.     // Start is called before the first frame update
    53.     private void Start()
    54.     {
    55.         player = GameObject.FindGameObjectWithTag("Player");
    56.  
    57.         playerController = player.GetComponent<PlayerController>();
    58.  
    59.         rb = GetComponent<Rigidbody>();
    60.  
    61.         playerLocked = false;
    62.  
    63.         chaseState = true;
    64.  
    65.         shouldBulletSpawn = false;
    66.  
    67.         playerPropeller = player.transform.GetChild(2).gameObject;
    68.     }
    69.  
    70.     private void FixedUpdate()
    71.     {
    72.         move();
    73.         if ((player.transform.position.x - this.transform.position.x) < 50)
    74.         {
    75.             chaseState = false;
    76.         }
    77.         else
    78.         {
    79.             chaseState = true;
    80.         }
    81.  
    82.         while (player.transform.position.y > this.transform.position.y)
    83.         {
    84.             moveUp();
    85.         }
    86.     }
    87.  
    88.     private static bool bruh = false;
    89.  
    90.     private void Update()
    91.     {
    92.         Quaternion lookRotation = Quaternion.LookRotation(playerPropeller.transform.position - transform.position);
    93.  
    94.         if (chaseState)
    95.         {
    96.             transform.rotation = lookRotation;
    97.             transform.Rotate(lookRotation.x, lookRotation.y + 93, lookRotation.z, Space.World);
    98.  
    99.             RaycastHit hit;
    100.  
    101.             if (Physics.Raycast(propeller.transform.position, player.transform.position, out hit, 140))
    102.             {
    103.                 shouldBulletSpawn = true;
    104.             }
    105.             else
    106.             {
    107.                 shouldBulletSpawn = false;
    108.             }
    109.         }
    110.         else
    111.         {
    112.             transform.rotation = lookRotation;
    113.             transform.Rotate(lookRotation.x, lookRotation.y + 93, lookRotation.z, Space.World);
    114.  
    115.             RaycastHit hit1;
    116.  
    117.             if (Physics.Raycast(propeller.transform.position, player.transform.position * 80, out hit1, 80))
    118.             {
    119.                 playerLocked = true;
    120.                 //Debug.Log("LOCKED ON PLAYER -PLANE");
    121.             }
    122.             else
    123.             {
    124.                 playerLocked = false;
    125.                 //Debug.Log("NOT LOCKED ON PLAYER -PLANE");
    126.             }
    127.  
    128.             if (playerLocked)
    129.             {
    130.                 shouldBulletSpawn = playerLocked;
    131.                 shouldRocketSpawn = playerLocked;
    132.             }
    133.             else
    134.             {
    135.                 shouldBulletSpawn = playerLocked;
    136.                 shouldRocketSpawn = playerLocked;
    137.             }
    138.         }
    139.  
    140.         propeller.transform.Rotate(0, 0, 90);
    141.  
    142.         rotateCorrect = new Quaternion(this.transform.rotation.x, this.transform.rotation.y, this.transform.rotation.z, this.transform.rotation.w);
    143.  
    144.         bulletCount = bulletParent.transform.childCount;
    145.         if (shouldBulletSpawn && bulletCount < 50)
    146.         {
    147.             for (int i = 0; i < 4; i++)
    148.             {
    149.                 Instantiate(bullet1, spawnPlaces[i].transform.position, rotateCorrect, bulletParent.transform);
    150.             }
    151.         }
    152.  
    153.         rocketCount = rocketParent.transform.childCount;
    154.         if (shouldRocketSpawn && rocketCount < 2)
    155.         {
    156.             for (int i = 0; i < 1; i++)
    157.             {
    158.                 Instantiate(rocket1, rocketSpawnPlaces[Random.Range(0, 2)].transform.position, rotateCorrect, rocketParent.transform);
    159.             }
    160.         }
    161.  
    162.         if (enemyAircraftHealth <= 0 && bruh == false)
    163.         {
    164.             die();
    165.             // Destroy(gameObject.transform.parent.gameObject);
    166.         }
    167.     }
    168.  
    169.     private void die()
    170.     {
    171.         ucakDus.Play();
    172.         bruh = true;
    173.  
    174.         Destroy(gameObject);
    175.     }
    176.  
    177.     private void move()
    178.     {
    179.         rb.AddRelativeForce(Vector3.left * speed);
    180.     }
    181.  
    182.     private void moveUp()
    183.     {
    184.         rb.AddRelativeForce(Vector3.up * speed);
    185.     }
    186.  
    187.     private void OnTriggerEnter(Collider other)
    188.     {
    189.         if (other.CompareTag("Rocket"))
    190.         {
    191.             other.GetComponents<AudioSource>()[1].Play();
    192.             other.GetComponent<RocketGo>().wait(other.gameObject);
    193.  
    194.             enemyAircraftHealth = 0;
    195.         }
    196.         else if (other.gameObject.CompareTag("Bullet"))
    197.         {
    198.             enemyAircraftHealth--;
    199.         }
    200.         else if (other.gameObject.CompareTag("Bina"))
    201.         {
    202.             enemyAircraftHealth = 0;
    203.  
    204.             Destroy(other.gameObject);
    205.         }
    206.         else if (other.gameObject.CompareTag("EnemyRocket"))
    207.         {
    208.             Destroy(other.gameObject);
    209.             enemyAircraftHealth = 0;
    210.         }
    211.     }
    212. }
     
  40. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    While it's not a huge deal, try to reduce the multiposting a bit. It makes it harder to follow any given discussion. You can also edit posts, if you forgot to mention something or want to include code a couple minutes later :)

    Whenever you do something along the lines of "if condition, x = true, else x = false" remember that the condition you use is itself a boolean expression, so this is equal to just saying x = condition (or x = !condition for negations).
    You do this a lot too, so it's not just that location ;)

    Further: be extremely careful when using while loops within things that are themselves loops (which Update, FixedUpdate, .. effectively are since Unity calls them on a loop). This has the potential to become an infinite loop. Well, technically it always has the potential, but usually you dont want while loops while already in Unity loop. That's oftentimes a misunderstanding. The default Unity workflow runs on one thread. You are telling Unity to repeat doing something until this condition is broken. This means that until this loop finishes, Unity wont do anything else. Nothing will ever be executed or applied, no new frame will ever be rendered. Units is stuck in your loop. Unless the code within that loop resolves the condition, Unity will freeze and crash.

    You only add forces, but these wont be applied this frame.. so the moveUp() function does infact not resolve the condition.
     
    Last edited: Aug 12, 2023
    enesbagci2332 likes this.
  41. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    It might be I guess
     
  42. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    I will be careful with posting from now on, thanks!

    do you think if I change it from while to if, that might fix it?

    I tried playing a little and it got better!

    https://drive.google.com/file/d/18B8xZVFI3iWNkrUf5FfIjl68Ni_LxXBP/view?usp=sharing
     
    Last edited: Aug 12, 2023
  43. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    Yes, since Units already runs FixedUpdate in a loop for you, if will make it so you apply forces each frame until the condition is not true anymore. On a note, controlling things using forces is a pain. It's very math'y. To do this precisely you would need to calculate how much force you need to add such that it approaches the correct altitude. Instead you simply add force while under a certain altitude, meaning the upwards velocity keeps accumulating. Maybe, when reaching that altitude, it has 100m/s upwards velocity and thus drastically overshoots the target.

    More often than not (i'd say about 95% of games or so) you really want a CharacterController and handle movement without physics. Rigidbodies are more for physics simulations, like ragdolls. Certainly not impossible to make a game with that, but a lot harder (while looking easier, thus also being a mild beginner trap).

    Edit: Do the crashes still happen?
     
    enesbagci2332 likes this.
  44. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82
    Believe me next time, I'm gonna make a little silly horror game. NO PSYCHICS.

    Answer to your edit:

    Kinda!

    So I tried playing the game like I told you guys in the post before. The game actually stopped crashing! (for now at least) But there is still a problem. I killed the enemy plane as I shot him it's health is 0 when all other enemies were able to die before it, it wasn't, my rocket was just triggering it again and again.
     
  45. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    That's a great exercise for debugging tho. Use Debug.Log() to check whether the correct code is executed, and to check the values of variables and conditions. Somewhere your game disagrees what should happen from your understanding of what should happen regarding the death of your last enemy. Find what's causing it, reason about why it's causing it, then fix that. If you get stuck feel free to ask again!
     
    enesbagci2332 likes this.
  46. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82


    LET'SSSS GOOOOOOO (for now)

    GAME IS WORKING PRETTY GOOD. I get frame drops sometimes. my best fps is 60fps and worst is 15fps.
     
  47. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,588
    Use the profiler to inspect the spikes in frametime. Check for things you wrote and home in on what may cause them. Then reason about why and fix that too! :)
     
    enesbagci2332 likes this.
  48. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82


    The game works great, I will try to stop those spikes!

    Other than that I will add some stuff like rocket blowing up so it can only destroy one thing. And some stuff and the game will be ready to go!


    Thanks, everyone! (AGAIN)
     
    wideeyenow_unity likes this.
  49. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    This is the only thing I see that can be picked on, because if you only have one player it can easily just be a singleton(static reference to said script). But it's really not that big of a deal, to be honest, FindWithTag() is much better than using GameObject.Find().

    But code is very exacting, so you want to be exact in all you do. Using the print() function is something I do a lot, to see what each frame is doing, and to make sure everything is in proper order in each frame.

    But coroutines kinda mess all that up, since they "technically" make their own script and run separately from the script they are in. That's why they can easily compound on themselves, and as you saw easily crash the game.

    There are a bunch of suggestions I could make, but you honestly don't need them yet. Just get everything working, and most importantly "performantly". Then once everything works, and the game is playable, then go back and criticize all the little things.

    Me personally, when I'm stuck, I just switch to different project(game) I'm working on, and somehow always come to the same problem I was stuck on before. But wind up seeing it in a different light(way), and come up with a solution, then re-incorporate that fix in the other one. Yup, I'm weird... lol...

    But first and foremost, just get it working first! :cool:
     
    enesbagci2332 likes this.
  50. enesbagci2332

    enesbagci2332

    Joined:
    Apr 4, 2021
    Posts:
    82

    I was wondering how can I create a singleton as you said for my script.