Home > OS >  Enable and disable GameObject on onstaytrigger
Enable and disable GameObject on onstaytrigger

Time:11-22

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StayonGallery2 : MonoBehaviour
{
    public GameObject G1;
    public GameObject G2;
    void Start()
    {
        G1.SetActive(false);
        G2.SetActive(false);
        
    }

    private bool _isStay;

    void OnTriggerStay(Collider player)
    {
        if (player.gameObject.tag == "Player")
        {
            _isStay = true;
        }
           
    }

    void Update()
    {
        if (_isStay)
        {
            _isStay = false;
            
            if (Input.GetKeyDown("g")) //If G is pressed
            {
                if (!G1.activeInHierarchy)
                {
                    G1.SetActive(true);
                    G2.SetActive(false);
                }
                else if (G1.activeInHierarchy)
                {
                    G1.SetActive(false);
                    G2.SetActive(true);
                }
            }

        }
    }
}

When I press G, G1 should activate and when I press G again, G1 will deactivate and G2 will activate.

I noticed that the frames everysecond on the Ontriggerstay causes if else statement to do it twice or trice in a single press of G. But in this code even if I use delay, It still doesn't work.

CodePudding user response:

From Unity docs: https://docs.unity3d.com/ScriptReference/Input.html

Note: Input flags are not reset until Update. You should make all the Input calls in the Update Loop.

Don't use Input in any physics callbacks, use it in Update or LateUpdate. You can record the trigger state then check keyboard state later.

private bool _isStay;

private void OnTriggerEnter(Collider player)
{
    if (player.gameObject.tag == "Player")
        _isStay = true;
}

void OnTriggerExit(Collider player)
{
    if (player.gameObject.tag == "Player")
        _isStay = false;
}

void Update()
{
    if(_isStay)
    {
        if (Input.GetKeyDown("g")) //If G is pressed
        {
            ...
        }
    }
}
  • Related