Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved Are there any disadvantages to this approach? (re-calling a method from a method on a condition)

Discussion in 'Scripting' started by gjaccieczo, Aug 19, 2021.

  1. gjaccieczo

    gjaccieczo

    Joined:
    Jun 30, 2021
    Posts:
    306
    I have a simple if statement:

    Code (CSharp):
    1.  
    2.  
    3. public void AMethod()
    4. {
    5.      //AMethod works and does its thing
    6.      if (something == some value)
    7.      {
    8.             AMethod();
    9.      }
    10. }
    11.  
    12.  
    something is equal to some value very rarely and after running AMethod() stops being equal to some value.
    AMethod() is also called rarely.

    My questions are:
    • what are the disadvantages of doing so?
    • what are the alternatives if a method needs to be re-called from within the same method?
    Thank you for your answers!
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Having a method call itself is fine, as long as you're careful to ensure it can't get caught in an infinite loop. Remember that anything in your function that's after the self-call won't happen until the self-call is completely finished (but will still happen, if you don't do anything to stop it).

    See also: Recursion
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    This is called recursion, as Anti points out above.

    To understand recursion, you must first understand recursion.
     
  4. gjaccieczo

    gjaccieczo

    Joined:
    Jun 30, 2021
    Posts:
    306
    Thank you for your response, Antistone! Yes, that's the word i was looking for, thank you!

    Thank you for your response, Kurt-Dekker! To understand anything you must first understand understanding :).
     
    Kurt-Dekker likes this.