Reputation: 339
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");
}
}
}
}
Upvotes: 3
Views: 3508
Reputation: 959
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.
Upvotes: 0
Reputation: 11916
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);
}
}
}
Upvotes: 4
Reputation: 5920
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;
Upvotes: 0