How can I check if an object has entered a trigger with a script attached to a different object?
If I have the player walk into something that is a trigger with a certain tag, how can I set a boolean to true and check that it's true with a script attached to a different object?
Grab a reference of it and check the variable. If you set it to true on the player and it's a public variable then you can grab it from a reference script by any from in the scene.
Answer by jdean300 · Jun 20, 2016 at 08:45 AM
public class Player : MonoBehaviour
{
public bool EnteredTrigger;
public void OnTriggerEnter(Collider other)
{
if (other.tag == /*the tag*/)
EnteredTrigger = true;
}
}
public class OtherScript : MonoBehaviour
{
private GameObject m_Player;
private void Start()
{
m_Player = GameObject.FindWithTag("Player");
}
private void Update()
{
if (m_Player.GetComponent<Player>().EnteredTrigger)
//Do whatever
}
}
And for more accurate, you can also create a variable for the object generating the collision
public class Player : $$anonymous$$onoBehaviour
{
public bool EnteredTrigger;
public GameObject CollisionWith;
public void OnTriggerEnter(Collider other)
{
if (other.tag == /*the tag*/)
EnteredTrigger = true;
CollisionWith = other.gameObject;
}
}
public class OtherScript : $$anonymous$$onoBehaviour
{
private GameObject m_Player;
private void Start()
{
m_Player = GameObject.FindWithTag("Player");
}
private void Update()
{
if (m_Player.GetComponent<Player>().EnteredTrigger)
{
//Do whatever
}
}
}
Your answer
Follow this Question
Related Questions
How to swap textures, only within an objects confines? 0 Answers
TRIGGER TO LAUNCH GAME 2 Answers
Fade an object when player enters a trigger 0 Answers
How to load an audiosource on trigger once? 2 Answers
Using particle trigger with tags 0 Answers