Search Unity

WaitForSeconds issue.. :(

Discussion in 'Scripting' started by Sabakey, Jan 8, 2018.

  1. Sabakey

    Sabakey

    Joined:
    Jan 8, 2018
    Posts:
    1
    Hi i want my player to wait 5 sec before he respawns but with this script, the game "teleports" him directly when he touched the collider..

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class RetourA0 : MonoBehaviour {
    6.     public GameObject personnage;
    7.     public GameObject start;
    8.     // Use this for initialization
    9.     void Start () {
    10.     }
    11.  
    12.     void OnTriggerEnter (Collider A) {
    13.         if (A.gameObject.tag == "Player") {
    14.             StartCoroutine ("Pause");
    15.             A.transform.position = start.transform.position;
    16.  
    17.         }
    18.     }
    19.  
    20.     IEnumerator Pause (){
    21.         Debug.Log ("mabeut debut");
    22.         yield return new WaitForSeconds (5f);
    23.         Debug.Log ("mabeut FIN");
    24.     }
    25.  
    26.  
    27.     void Update () {
    28.  
    29. }
    30. }
    Thanks a lot for your help :)
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    You need to put the teleport part at the end of your coroutine. Coroutines don't pause your code. For your code, it will run the start part of the coroutine and then yield for 5 secs, which allows other code to run. Basically when it hits the yield, your teleport gets to trigger. After 5 secs, the rest of the coroutine gets a chance to run.
     
  3. ihgyug

    ihgyug

    Joined:
    Aug 5, 2017
    Posts:
    194
     
    Last edited: Jan 8, 2018
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    That isn't going to work as the Pause doesn't know what A is. The gameobject will need to be passed to the coroutine.

    @Sabakey Also note you should use the method version of starting your coroutine as you can easily pass parameters that way vs the string call.

    Code (CSharp):
    1. StartCoroutine(Pause()); //Method version
    2.  
    3. StartCoroutine(Pause(A)); //Method version with param
    4.  
    5. IEnumerator Pause (GameObject A) //Pass the gameobject to your coroutine.
    6.  
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    That's confusing when someone modify's a quote lol