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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

(SOLVED) WaitForSeconds OnTriggerEnter

Discussion in 'Scripting' started by leonhouse, Aug 21, 2017.

  1. leonhouse

    leonhouse

    Joined:
    Aug 1, 2017
    Posts:
    7
    I'm trying to Enter a trigger call a function which sets a bool to true then wait for a second or two and then set the bool to false and also Debug.Log to tell me it worked. The code I currently have doesn't give me any errors, but it is only setting the bool to true and destroying the gameObject from there it doesn't seem to do anything. If you can help solve my issue it would be greatly appreciated!

    My code is this currently:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class DoubleNuggets : MonoBehaviour
    6. {
    7.  
    8.     private GameObject doubler;
    9.  
    10.     private void Start()
    11.     {
    12.         doubler = GameObject.FindWithTag("coinmanager");
    13.  
    14.     }
    15.  
    16.     IEnumerator OnTriggerEnter(Collider collision)
    17.     {
    18.             doubler.GetComponent<CoinsManager>().shouldDouble = true;
    19.             Destroy(gameObject);
    20.             yield return new WaitForSeconds(1);
    21.             doubler.GetComponent<CoinsManager>().shouldDouble = false;
    22.             Debug.Log("Worked");
    23.         }
    24.         }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,151
    SInce you are destroying the gameObject, the script stops running. Nothing after the destroy will run because the object no longer exist to keep running.
     
  3. leonhouse

    leonhouse

    Joined:
    Aug 1, 2017
    Posts:
    7
    I figured that out right before you replied thank you though Brathnann! lol.
     
  4. leonhouse

    leonhouse

    Joined:
    Aug 1, 2017
    Posts:
    7
    Another question though how do I get it to destroy the gameobject and still be able to access the script? Is there a way to access the sprite renderer and just turn it off and then destroy gameobject after I set it false?
     
  5. leonhouse

    leonhouse

    Joined:
    Aug 1, 2017
    Posts:
    7
    Nevermind I figured that out also! I used gameObject.GetComponent<Renderer>().enabled = false; and it set it to disable the sprite, but keep the gameObject until after the wait time. All good here now.
     
  6. cihannakgul

    cihannakgul

    Joined:
    Oct 24, 2019
    Posts:
    15
    Bro.. I gotta write it, i was looking around for problem and you solve it... :) thank u very much!