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

Question Half of a script is not read anymore after reloading the scene

Discussion in 'Scripting' started by WashinoStudio, Oct 3, 2023.

  1. WashinoStudio

    WashinoStudio

    Joined:
    Apr 18, 2023
    Posts:
    6
    Hello,
    First post here, tell me if I'm in the wrong post place.

    I encountered a problem in one of my scripts while developping a game: the 2nd half of the script isn't read anymore after I reloaded my scene with SceneManager.LoadScene.

    Here is the script:

    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. public class PlayerAttackAnimation : MonoBehaviour
    5. {
    6.     //public float playerAttackDamage;
    7.     public Animator animator;  
    8.     public PlayerMovement playerMovement;
    9.     public BulletShotInstantiate bulletShotInstantiate;
    10.     public bool isAttackingNow = false;
    11.  
    12.  
    13.     void Update()
    14.     {
    15.         //isInAttackMODE
    16.  
    17.  
    18.         if (playerMovement.isInAttackMode == true)
    19.         {
    20.            
    21.             if (Input.GetKey(KeyCode.UpArrow) && Input.GetKeyDown(KeyCode.Keypad1))
    22.             {
    23.                 animator.SetTrigger("isUpAttacking");
    24.                 StartCoroutine(IsAttackingNow());
    25.             }
    26.  
    27.             else if (Input.GetKey(KeyCode.DownArrow) && Input.GetKeyDown(KeyCode.Keypad1))
    28.             {
    29.                 animator.SetTrigger("isDownAttacking");
    30.             }
    31.  
    32.             else if (Input.GetKeyDown(KeyCode.Keypad1))
    33.             {              
    34.                 animator.SetTrigger("isAttacking");
    35.                 StartCoroutine(IsAttackingNow());
    36.             }
    37.         }
    38.  
    39.  
    40.  
    41.        //IsInShotMODE
    42.  
    43.  
    44.         if (playerMovement.isInShotMode == true && bulletShotInstantiate.canShoot == true)
    45.         {
    46.  
    47.            Debug.Log("AbleToShot");
    48.  
    49.             if (Input.GetKey(KeyCode.UpArrow) && Input.GetKeyDown(KeyCode.Keypad1))
    50.             {
    51.                
    52.                 animator.SetTrigger("isUpShoting");
    53.                 Debug.Log("ShotAnimation");
    54.             }
    55.  
    56.            if (Input.GetKeyDown(KeyCode.Keypad1))
    57.            { Debug.Log("ShotAnimation");
    58.                 animator.SetTrigger("isShoting");
    59.              
    60.            }
    61.  
    62.         }  
    63.  
    64.     }  
    65.  
    66.     private IEnumerator IsAttackingNow()
    67.     {
    68.         isAttackingNow=true;
    69.  
    70.         yield return new WaitForSeconds(0.5f);
    71.  
    72.         isAttackingNow = false;
    73.     }
    74.  
    75. }
    76.  

    Everything is doing well at first time while launching the game, 0 problem at this moment.

    Then, when I reload the game after the player died,all the second part of the script (below the //isInShotMODE) does not work anymore, but the first one (above the//isInShotMODE) does work perfectly.

    Which means, if I want to attack, the animations are played well but if I want to shot, the projectil is instantiate but the animation linked to the shot is not played anymore.

    I tried to use Debug.Log to identify where my problem is and surprisingly, the first one Debug.Log (Debug.Log("AbleToShot"); ) is working fine.
    After the scene reload, the 2 conditions here :
    Code (CSharp):
    1. if (playerMovement.isInShotMode == true && bulletShotInstantiate.canShoot == true)
    are still respected and the message is showed in the console.
    .
    However, the second one and third one Debug.Log("ShotAnimation") aren't showed in the console when I press Keypad1. That means that my if() functions are not read anymore and I can't tell why...
    Those are the same functions and the same keypad as the first time I launched the game and the condition in the if() is just pushing a button down..

    Has any of you an idea to help in this situation please ?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Keep using it... you're not done!

    For one, I notice you have nothing preventing you from starting this coroutine twice. You set and clear a boolean in the coroutine but you never check it to inhibit multiple calls to the coroutine, so it does nothing for you.

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
    APSchmidtOfOld and Bunny83 like this.
  3. WashinoStudio

    WashinoStudio

    Joined:
    Apr 18, 2023
    Posts:
    6
    I'm not sure to understnad what you said. Is there a problem with the boolean I use ?

    That's what I did 3 times to see if my code is running in the differents if() statement.
    I know now that it doesn't. My problem is that I dont understand why, because it is just a if() function with one simple condition.
    In which condition is it possible that a if() statement can't be read at all ?
     
  4. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    541
    If the coroutine is still active and you activate another then the isAttackingNow bool will be prematurely set to false by the previously activated coroutine that's about to end. Instead you can stop the coroutine before starting another.
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,507
    As above, it's amazing how many times I see code that starts a coroutine without any control of how to stop it or that you can start multiple overlapping coroutines of the same code; it's a big source of errors.

    This is why StartCoroutine returns you a value: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

    This would easily be found though if you debug it with Debug.Log or just attach a debugger to it.
     
    APSchmidtOfOld likes this.
  6. WashinoStudio

    WashinoStudio

    Joined:
    Apr 18, 2023
    Posts:
    6
    Thanks for your answers guys, I added a StopCoroutine() at the end of mine (and I confess, I'm pretty new with C# and I didn't even know that coroutine could (has to?) be stopped... my bad!)
    But the coroutine I use only impacts the first part of my code, and I don't have problem with it.

    The problem I encounter is on the 2nd part of the code, and there is no coroutine in this part.

    I tried to run a reloaded scene to see if the modification of the coroutine in the first part as an impact on the 2nd part but nothing as changed.

    Is there something else I can do to fix the script not read after the scene reload ?
     
  7. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    541
    There's no need to use StopCoroutine() at the end of your coroutine, by then it's already going to stop anyway. You stop the coroutine before starting another one. And you don't always need to stop a coroutine, it just depends on what your code is doing.

    Code (CSharp):
    1.       if (Input.GetKey(KeyCode.UpArrow) && Input.GetKeyDown(KeyCode.Keypad1))
    2.       {
    3.             animator.SetTrigger("isUpAttacking");
    4.             StopAllCoroutines();
    5.             StartCoroutine(IsAttackingNow());
    6.       }
     
    APSchmidtOfOld likes this.
  8. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    541
    To address your bigger issue, I've also had problems with reloaded scenes not behaving as expected and I found that it was a result of Random not being predictably random. I solved it by resetting the Random state. But I can't see this being your problem unless you're setting isInAttackMode randomly. :)
     
    Last edited: Oct 4, 2023
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
  10. WashinoStudio

    WashinoStudio

    Joined:
    Apr 18, 2023
    Posts:
    6
    Thanks for advice, I really do appreciate the informations, but that's not my point.
    Do you have any advice like this about the problem I mention above please ?
     
  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Yes. See my first post for how to debug. Nobody here can do that for you.
     
  12. WashinoStudio

    WashinoStudio

    Joined:
    Apr 18, 2023
    Posts:
    6
    I never ask anybody to do it for me, I just want to understand why a if() statement which is prefectly running when the game is launched, can't be executed even if the conditions inside are verified when the scene is reloaded. May be I didn't see something wrong in my code and that's what I'm looking for.

    You said:
    I'm in the first case: my code isn't running at all and I don't understand why.

    That's what I did to see where my problem is. I found this: when the scene is reloaded, the 2 last if() statements which have a button pushed as condition are not working if I push the right keypad.

    To answer these questions:
    -Yes it runs fine at the first time I launch the game
    - the first part is working great at any time, the second one works only the first time the game is launched
    - As most of the content of the update() function is if() statement, it runs when I call them while verifying the required conditions
    -It runs in the order I described in the code: if I'm in attack mode , the attack animation is played. If I'm in shot mode, the shot animation is played except when I reload the scene.


    Thanks for this info, I didn't know the Debug.Log() could have a 2nd argument ! I tried it, but the problem I have is that my debug.log() aren't read, so they are not showed in the console.


    Same here, I didn't know the Debug.Break(). I used the pause button directly in Unity to see the different status of my variables, scripts etc... And everything is good when I reload the scene, at least as good as the first time I launch the game. I have the same scripts and the same boolean variables activated.

    And finally, my problem is not with RayCast or distance, I'm not working on mobile device, I don't do VR, my problem is not linked to On-Collision().

    As you can see, I entirely read and looked for help in your first post. And many of your suggestions are what I have done, but I'm still here with the same problem.
    That's why I wonder if someone has already seen this type of problem or can have a different approach than mine to fix it.
     
  13. WashinoStudio

    WashinoStudio

    Joined:
    Apr 18, 2023
    Posts:
    6
    Here something new about what I tried:

    1- I tried this :
    Code (CSharp):
    1. if (playerMovement.isInShotMode == true && bulletShotInstantiate.canShoot == true)
    2. {
    3. animator.SetTrigger("isShoting");
    4. }
    5.  
    I removed the KeyPad pushed conditions and it works perfectly as long as the 2 above conditions are verified.

    In this case, my problem is :
    Code (CSharp):
    1. if (Input.GetKey(KeyCode.Keypad1))
    Why isn't this line read ?

    2- Instead of using GetKeyDown to trigger the shot animation in the if() statement, I used GetKey.
    It still doesn't play the shot animation if I just push the KeyPad1 once, but if I keep pushing KeyPad1, the shot animation is played with ~1sec delay and keeps playing as long as I maintain the keypad1.
    I still don't understand why.. but this:

    Code (CSharp):
    1. if (Input.GetKey(KeyCode.Keypad1))
    2.                 {        
    3.                     animator.SetTrigger("isShoting");
    4.                 }
    is able to play the animation with a delay. I think this delay created here is the main reason why the animation can't be played with GetKeyDown.. But I can't figured out where comes this delay from..

    Does anyone has already encountered something similar like this and understand why it behaves like this ?
     
  14. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Read up a little bit on the difference between
    Input.GetKey()
    and
    Input.GetKeyDown()


    I suspect you want the latter, based on your setting of a Animator trigger property.

    Consider also making a spelling pass on your game... "isShoting" is misspelled:

    This is technically fine if you misspell it precisely wrongly in all cases.

    However it is a future minefield waiting for you to spell it correctly in one place and now you have a VERY mysterious bug. See below.

    It's always better and more repeatable to spell it precisely correct in all cases.

    Have you opened the Animator window while this is going on? Animation state transitions can be configured to wait until the current loop is complete before transitioning. Look for "Has Exit Time" and see the docs for what it means.

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.
     
  15. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    326
    Well if an if statement is not executing, there are really only two possibilities:

    1. Your if condition is not met: in your case it means
    playerMovement.isInShotMode
    is false or
    bulletShotInstantiate.canShoot
    is false (or both of them are false)

    2. An exception is being thrown before the if statement.

    Time to debug as @Kurt-Dekker said. Using breakpoints and going step by step in your code will immensely help in this situation.

     
    Kurt-Dekker likes this.