Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Help Wanted The method is executed twice when the button is pressed

Discussion in 'Scripting' started by a4chteam, Apr 18, 2021.

  1. a4chteam

    a4chteam

    Joined:
    Dec 22, 2020
    Posts:
    16
    Code (CSharp):
    1. void Update()
    2. {
    3.         if (Input.GetButtonDown("Use"))
    4.         {
    5.             StartCoroutine(Interaction(true));
    6.         }
    7. }
    Code (CSharp):
    1. public IEnumerator Interaction(bool state)
    2.     {
    3.         if(state == true)
    4.         {
    5.             Check = Physics2D.Raycast(new Vector2(transform.position.x, transform.position.y), RayDirection, RayLength, Mask);
    6.             if (Check.collider != null)
    7.             {
    8.                 if (Check.collider.tag == "Dialogue")
    9.                 {
    10.                     state = false;
    11.                     yield return new WaitForSeconds(0.5f);
    12.                     Debug.Log("is work");
    13.                 }
    14.             }
    15.         }
    16.     }
    The console displays the message twice "is work";
    Please tell me what is the error? I need the message to be displayed only once.
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    1,878
    Make sure you only have the upper code part on one script on one gameobject. Otherwise, they both will start a coroutine at the same time and thus two of them will be executed and the message will appear twice.
    GetButtonDown should only be true for one frame and your coroutine does not contain loops, so that would be my guess.
     
    Joe-Censored, a4chteam and SparrowGS like this.
  3. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,517
    Probably two callers or two scripts, Debug.Log to see the stacktrace
     
    Joe-Censored and a4chteam like this.
  4. a4chteam

    a4chteam

    Joined:
    Dec 22, 2020
    Posts:
    16
    Thank you for your answers!
     
unityunity