A
A
a2022-03-19 13:39:46
Unity
a, 2022-03-19 13:39:46

How to check if an object is in a trigger?

Good afternoon! Essence of the question: I have a button, and if you enter its trigger, it is activated (OnButtonStay()), and if you exit, it actually deactivates (OnButtonExit()), but if the object enters its trigger and then disappears (SetActive (false) ), then the button will remain active (OnButtonStay()). So here's how to make the script check if the object is in the trigger, and if it disappears or disappears, it simply deactivates the button (OnButtonExit()).
I would be very grateful for your help!

using UnityEngine;

public class ButtonTrigger : MonoBehaviour
{

    [SerializeField] private Animator _anim;
    [SerializeField] private MeshRenderer _buttonbase;
    [SerializeField] private Texture _materialOff;
    [SerializeField] private Texture _materialOn;

    [SerializeField] private AudioSource _onSound;
    [SerializeField] private AudioSource _offSound;

    private bool _isDown;

    private void Start()
    {
        _anim.SetBool("isDown", !_isDown);
    }

    private void OnTriggerStay(Collider other)
    {
        if (other)
        {
            OnButtonStay();
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other)
        {
            OnButtonExit();
        }
    }

    private void OnButtonStay()
    {
        _anim.SetBool("isDown", _isDown);

        _buttonbase.material.mainTexture = _materialOn;
    }

    private void OnButtonExit()
    {
        _anim.SetBool("isDown", !_isDown);
        _buttonbase.material.mainTexture = _materialOff;
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question