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

C# WaitForSeconds not working?

Discussion in 'Editor & General Support' started by DivineMango, Nov 5, 2014.

  1. DivineMango

    DivineMango

    Joined:
    Nov 5, 2014
    Posts:
    4
    In this game, I'm trying to implement a power-up system. Applying the power-up works fine, but when I try to set a time for it to wear off using WaitForSeconds, it either ignores the statement or acts as a "wall" in the code. However, in other scripts, WaitForSeconds works fine. Any help?
    Here is the code:

    using UnityEngine;
    using System.Collections;

    public class Powerup : MonoBehaviour
    {

    public int effect;
    public PlayerController playerController;

    void Start()
    {
    switch (transform.name)
    {
    case "speeder":
    effect = 0;
    break;
    case "inverter":
    effect = 1;
    break;
    case "passer":
    effect = 2;
    break;
    case "sizer":
    effect = 3;
    break;
    default:
    effect = -1;
    break;
    }
    }

    void OnTriggerEnter2D(Collider2D other)
    {

    Destroy(gameObject);

    if (other.transform.tag == "Player")
    {
    StartCoroutine(ApplyEffect(effect, other.gameObject));
    }
    }

    IEnumerator ApplyEffect(int effect, GameObject player)
    {
    playerController = player.GetComponent<PlayerController>();

    switch (effect)
    {
    case 0:
    playerController.horzMoveSpeed *= 2f;
    playerController.vertMoveSpeed *= 2f;
    yield return new WaitForSeconds(15);
    playerController.horzMoveSpeed /= 2f;
    playerController.vertMoveSpeed/= 2f;
    break;
    case 1:
    playerController.horzMoveSpeed *= -1;
    break;
    case 2:
    GameObject wall = GameObject.FindWithTag("wall");
    Physics2D.IgnoreCollision(player.collider2D, wall.collider2D);
    break;
    case 3:
    playerController.Shrink(.02035f, .01f, 30);
    break;
    }
    }
    }
     
  2. drewradley

    drewradley

    Joined:
    Sep 22, 2010
    Posts:
    3,063
    Try moving it out of the switch and just using a simple "if" statement after the switch. You seem to only be wanting to wait in effect == 0 anyway.
     
  3. DivineMango

    DivineMango

    Joined:
    Nov 5, 2014
    Posts:
    4
    Thanks for the suggestion, but I tried changing the switch to an if and the WaitForSeconds statement stopped everything after it.
     
  4. Ruekaka

    Ruekaka

    Joined:
    Sep 12, 2014
    Posts:
    119
    Could it be, that every condition must have a yield return?