How to Wait 5 second after trigger is activated? - c#

I am trying to wait five seconds after the trigger is met then after the five seconds is up i want to go to the next scene. The problem is that once the trigger is met the it automatically goes to the next scene.
What I have tried
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
IEnumerator WaitAndDie()
{
yield return new WaitForSeconds(5);
}
void Update()
{
StartCoroutine(WaitAndDie());
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Update();
Application.LoadLevel("GameOverScene");
return;
}
}
}
I have also tried
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
IEnumerator WaitAndDie()
{
yield return new WaitForSeconds(5);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
StartCoroutine(WaitAndDie());
Application.LoadLevel("GameOverScene");
return;
}
}
}

Only call Application.LoadLevel after yield return :).
IEnumerator WaitAndDie()
{
yield return new WaitForSeconds(5);
Application.LoadLevel("GameOverScene");
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
StartCoroutine(WaitAndDie());
return;
}
}
}

This should work
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
bool dead;
IEnumerator OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
yield return new WaitForSeconds(5);
Application.LoadLevel("GameOverScene");
dead = true;
return dead;
}
}
}

Related

My unity project is Freezing with this script i don't know what have i done wrong

My unity project is freezing and there are no errors before clicking play button after that it freezes the code:
In this code I am trying to detect if the player is triggering enemy collider with OnTriggerStay2D
so if it does I want the code to add score every second with IEnumerator function. But if the player is not colliding with the enemy for more than 2 seconds it gets destroyed.
The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trigger : MonoBehaviour
{
public GameObject other;
bool touching = false;
int score = 0;
public void Update()
{
AddScore();
}
private void OnTriggerStay2D(Collider2D other)
{
Debug.Log("Touching");
touching = true;
}
public void AddScore()
{
if(touching == true)
{
while (touching == true)
{
score++;
StartCoroutine(wait());
}
Debug.Log(score);
}
else
{
Debug.Log("Not Touching");
StartCoroutine(waiter());
}
}
IEnumerator waiter()
{
yield return new WaitForSecondsRealtime(2);
Destroy(other);
}
IEnumerator wait()
{
yield return new WaitForSecondsRealtime(1);
}
}
Just delete while (touching == true), that is breaking your game.
The if condition should be enough for the logic.

Unity can't hear sound

I'm doing a football game and i want it to play a sound every time i score a goal but i can't hear any sound.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class gol : MonoBehaviour
{
public AudioClip audioclip;
public AudioSource audiosource;
public bool golmu = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
if (golmu == true && !audiosource.isPlaying)
{
audiosource.clip = audioclip;
audiosource.Play();
}
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "gol")
{
golmu = true;
}
else
{
golmu = false;
}
}
public void OnTriggerExit(Collider other)
{
if(other.gameObject.tag == "gol")
{
golmu = false;
}
}
}
I tried without using AudioClip but it's not working. Putting the AudioSource component in another object too. I tried every code I saw but it didn't work.

script to turn the light off and on [ C# , Unity 3d ]

I made this little script that should turn the light of a point light off and on ... unfortunately only the off button works, after which it doesn't turn on again .... maybe there is some error in the script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurnLight : MonoBehaviour {
public GameObject light;
private bool on = true ;
void OnTriggerStay(Collider other) {
if (other.tag == "Player" && Input.GetKey(KeyCode.E) && !on)
{
light.SetActive(true);
on = true;
}
else if (other.tag == "Player" && Input.GetKey(KeyCode.E) && on)
{
light.SetActive(false);
on = false;
}
}
}
Please Check this link to understand OnTriggerStay Function
On Trigger Stay
Also Please check those to differentiate between
Get Key and
Get Key Down
the problem is calling of OnTriggerStay happens continuously and you are using GetKey functions which will return true all times if the player pressed.
So when you use GetKey this will cause Single press on E will be redden multiple times.
Here is my solution
public GameObject light;
bool isPlayerStandingNear = false;
private void Update()
{
if(isPlayerStandingNear)
{
//Debug.Log("isPlayerStandingNear");
if(Input.GetKeyDown(KeyCode.E))
{
Debug.Log("Light State : "+ light.active);
light.SetActive(!light.active);
}
}
}
void OnTriggerStay(Collider other)
{
if (other.tag == "Player")
{
isPlayerStandingNear = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
isPlayerStandingNear = false;
}
}

Magnet power up Like subway surfers does not work

I am trying to make a Magnet power up like subway surfer. My game is a endless runner game. When the runner collide with the magnet, the coins attracting towards the player. But it is not working. After runner collide with the magnet and after that every time he collide with the coin below error keep coming.
NullReferenceException: Object reference not set to an instance of an object
Coin.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Coin.cs:37)
any one can help me?
Magnet Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Magnet : MonoBehaviour
{
// Start is called before the first frame update
public GameObject coinDetectorObj;
public static bool iscoinDetectorObj;
// Start is called before the first frame update
void Start()
{
coinDetectorObj = GameObject.FindGameObjectWithTag("coin detector");
coinDetectorObj.SetActive(false);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
StartCoroutine(ActivateCoin());
Destroy(transform.GetChild(0).gameObject);
}
}
IEnumerator ActivateCoin()
{
coinDetectorObj.SetActive(true);
yield return new WaitForSeconds(0.5f);
coinDetectorObj.SetActive(false);
}
}
Coin Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : MonoBehaviour
{
public Transform playerTransform;
public float moveSpeed = 17f;
CoinMove coinMoveScript;
void Start()
{
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
coinMoveScript = gameObject.GetComponent<CoinMove>();
}
void Update()
{
transform.Rotate(130 * Time.deltaTime, 0, 0);
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
FindObjectOfType<AudioManager>().PlaySound("PickUpCoin");
PlayerManager.numberOfCoins += 1;
Destroy(gameObject);
}
if (other.gameObject.tag == "coin detector")
{
coinMoveScript.enabled = true;
}
}
}
CoinMove Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinMove : MonoBehaviour
{
Coin coinScript;
// Start is called before the first frame update
void Start()
{
coinScript = gameObject.GetComponent<Coin>();
}
// Update is called once per frame
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, coinScript.playerTransform.position,
coinScript.moveSpeed * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
//Add count or give points etc etc.
Destroy(gameObject);
}
}
}

How to detect an object in a trigger?

I’ve placed in the scene an object with a trigger and I want the console sends me a message detecting if the player is in or out of the trigger when I click a button . When I play, it only sends me a message when the player is into the trigger.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapDetect : MonoBehaviour {
void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Player") {
Debug.Log ("Map ON");
}
else {
if (other.gameObject.tag == "Player") {
Debug.Log ("Map OFF");
}
}
}
}
Use OnTriggerEnter and OnTriggerExit instead of OnTriggerStay to keep the current state:
public class MapDetect : MonoBehaviour {
private bool isTriggered;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
isTriggered = true;
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
isTriggered = false;
}
void Update(){
if(Input.GetKey(KeyCode.Space)){
Debug.Log(isTriggered);
}
}
}
Your logic is totally wrong. You're only checking if the TRIGGER STAYS IN YOUR BOUNDS but still trying to log "Map OFF" message which will never happen.
Instead of OnTriggerStar method use OnTriggerEnter and OnTriggerExit. Then print the message only when needed ( or in debug mode ) :
void OnTriggerEnter(Collider other)
{
if ( other.gameObject.CompareTag("Player") )
{
m_IsPlayerOnTheMap = true;
}
}
void OnTriggerExit(Collider other)
{
if( other.gameObject.CompareTag("Player") )
{
m_IsPlayerOnTheMap = false;
}
}
void Update()
{
#if DEBUG
if ( m_IsPlayerOnTheMap )
{
Debug.Log("Map ON");
}
else
{
Debug.Log("Map OFF");
}
#endif
}
private bool m_IsPlayerOnTheMap = false;
Try:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapDetect : MonoBehaviour {
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
Debug.Log ("Map ON");
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
Debug.Log ("Map OFF");
}
}
}
This will switch it on when you enter and off when you exit (althout all it does right now is print the result).
Hope it helps.

Categories

Resources