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 How to repeat if statement

Discussion in 'Scripting' started by Megulan, Sep 13, 2023.

  1. Megulan

    Megulan

    Joined:
    Aug 17, 2021
    Posts:
    12
    Im trying to make enemy give me damage every 2 seconds when colliding but idk how to repeat it I tried many different ways


    private void OnCollisionEnter2D(Collision2D collision)
    {
    // Check if the collided object has the specified tag
    if (collision.gameObject.CompareTag(customTagToDetect) && canTakeDamage == true)
    {
    TakeDamage(20);
    canTakeDamage = false;
    }
    }

    I want that if TakeDamage(20); to work every 2 seconds if canTakeDamage is true and is colliding with specified tag how to do it?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    This approach to learning may be useful to you:

    Imphenzia: How Did I Learn To Make Games:



    Otherwise, start with "damage over time" type tutorials. No sense whatsoever someone trying to retype a complex graphical tutorial in this little tiny box!!

    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?

    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.


    If you have an ACTUAL problem,

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?



    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    - Do not TALK about code without posting it.
    - Do NOT post unformatted code.
    - Do NOT retype code. Use copy/paste properly using code tags.
    - Do NOT post screenshots of code.
    - Do NOT post photographs of code.
    - ONLY post the relevant code, and then refer to it in your discussion.
     
  3. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,104
  4. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Well there are many ways to achieve the same goal, but a simple way would just be using a simple timer setup:
    Code (CSharp):
    1. int timer;
    2. int framesPerSecond = 60; // if set?
    3.  
    4. void Update()
    5. {
    6.     if (!canTakeDamage)
    7.     {
    8.         timer++;
    9.         if (timer > framesPerSecond * 2) // 2 seconds
    10.         {
    11.             canTakeDamage = true;
    12.             timer = 0;
    13.         }
    14.     }
    15. }
    16.  
    17. private void OnCollisionEnter2D(Collision2D col)
    18. {
    19.     if (col.CompareTag(customTagToDetect) && canTakeDamage)
    20.     {
    21.         TakeDamage(20);
    22.         canTakeDamage = false;
    23.     }
    24. }
     
  5. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,834
    Why would you do this:

    Code (CSharp):
    1. int framesPerSecond = 60;
    2.         timer++;
    3.         if (timer > framesPerSecond * 2) // 2 seconds
    when you could do this:

    Code (CSharp):
    1.         timer += Time.deltaTime;
    2.         if (timer > 2f)
    You also need to decide when to clear the timer, such as just after dealing damage or being enabled.
     
    wideeyenow_unity likes this.
  6. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    521
    I'm going to suggest an alternative to the ideas already posted. I see CanTakeDamage as a calculation not a flag one sets with some other code unrelated to it and then some way to clear that flag unrelated to either of those.

    Is it the case that damage should be applied if collision with a particular object has occurred and either it just collided or 2 seconds elapsed since the last time? I think the logic can be added to TakeDamage or a wrapper method can test and then call TakeDamage so all you look for is a collision.

    I don't believe you need a timer you need to know the last time a collision occurred. If it has been more than 2 seconds then it is true. Shouldn't need a flag. You reset the last collision time if you call TakeDamage.

    In any case I think it will work.
     
    Megulan likes this.
  7. Megulan

    Megulan

    Joined:
    Aug 17, 2021
    Posts:
    12
    ty
    ty so much it helped me alot
     
  8. Megulan

    Megulan

    Joined:
    Aug 17, 2021
    Posts:
    12
    ty Ill use it next time since this is shorter way
     
  9. Megulan

    Megulan

    Joined:
    Aug 17, 2021
    Posts:
    12
    thats very good point Ill try to figure it out later
     
  10. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    Code (CSharp):
    1. int framesPerSecond = 60;
    2. timer++;
    3. if (timer > framesPerSecond * 2) // 2 seconds
    Well personally I have a static variable of "fps" which is calculated through code, also do one for deltaTime as I heard not doing multiple calls each case can be a micro performance. So it's just force of habit I guess.

    But even still, just using deltaTime would be a cleaner way, thanks for the heads up. :)
     
  11. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    521
    The benefit becomes evident when you imagine a need for CanReduceDamage functionality that should check say every 10 seconds. So another variable, another timer, another if expression and another thing to reset.

    By just calling a method named e.g. ApplyDamage all the related logic can be in one place. Not only do you avoid more clutter in Update (what is there can be removed) but the event that really matters OnCollisionEnter2D contains the trigger. BTW OnCollisionEnter2D is only fired on "enter" right? So you need to monitor OnCollisionStay2D to see if the player is still colliding.