Search Unity

Why is this code not working?

Discussion in 'Scripting' started by AV_Corey, Feb 9, 2016.

  1. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    So I want an object in my game to be deleted when the player touches it but instantiate again a few seconds after.

    This is my current code:

    Code (CSharp):
    1. public class JumpDot : MonoBehaviour
    2. {
    3.  
    4.       private Player player;
    5.  
    6.     void Start()
    7.     {
    8.  
    9.           player = FindObjectOfType <Player>();
    10.  
    11.     }
    12.  
    13.  
    14.       void OnTriggerEnter2D(Collider2D other)
    15.       {
    16.  
    17.           if (other.name == "Player")
    18.           {
    19.  
    20.               StartCoroutine("waitThreeSeconds");
    21.               player.currentJumps++;
    22.               player.canJump = true;
    23.               Destroy(gameObject);
    24.  
    25.           }
    26.  
    27.       }
    28.  
    29.       IEnumerator waitThreeSeconds()
    30.       {
    31.  
    32.           yield return new WaitForSeconds(3);
    33.           print("waited 3 seconds");
    34.  
    35.       }
    36.  
    37. }

    So in theory should this not be starting the three second coroutine when the dot is triggered and then printing the message correctly? I'm not seeing anything wrong with this code but I'm sure I'm just being stupid.
     
    Last edited: Feb 9, 2016
  2. krousty_bat

    krousty_bat

    Joined:
    Oct 9, 2012
    Posts:
    60
    you should insert your code like this for better lisibility ;)
    Code (CSharp):
    1. public class JumpDot : MonoBehaviour
    2. {
    3.   private Player player;
    4.  
    5.   void Start()
    6.   {
    7.   player = FindObjectOfType <Player>();
    8.   }
    9.  
    10.   void OnTriggerEnter2D(Collider2D other)
    11.   {
    12.     if (other.name == "Player")
    13.     {
    14.     StartCoroutine("waitThreeSeconds");
    15.     player.currentJumps++;
    16.     player.canJump = true;
    17.     Destroy(gameObject);
    18.   }}
    19.  
    20.   IEnumerator waitThreeSeconds()
    21.   {
    22.   yield return new WaitForSeconds(3);
    23.   print("waited 3 seconds");
    24.   }}
    25.  
     
  3. luke_2

    luke_2

    Joined:
    Nov 20, 2012
    Posts:
    29
    From the looks of it, the coroutine is being started, but then the gameobject is being destroyed. As the coroutine is being run as part of the gameobject, the coroutine will get stopped as part of the gameobject destruction.
     
  4. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    You are correct. Thankyou very much for pointing out my stupid mistake haha.