Why Isn't My Break Glass Script Working?
In my game im trying to make it so when the player is on the trigger it will check if they pressed E and if they do it will destroy the glass heres my script
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GlassBreak : MonoBehaviour {
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
OnMouseDown();
}
}
void OnMouseDown()
{
if (Input.GetKeyDown(KeyCode.E))
{
Destroy(gameObject);
}
}
}
Quick reply. I haven't use OnTriggerEnter2D() before, but I think the idea is the same as OnTriggerEnter()? If so then it is only triggered at the first frame the player enter a Collider Trigger. So your On$$anonymous$$ouseDown() will only be called at that frame, which makes it nearly impossible for Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E) to be true.
Answer by Cuttlas-U · Oct 23, 2017 at 06:44 PM
hi;
i think its better to create a bool variable and check with that ; so this way u make a bool to true each time u enter the trigger and make it false again when u exit; then in OnMouseDown function when u click on the object u check that variable to see if its true or not;
public bool BreakGlass = false;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
BreakGlass = true;
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
BreakGlass = false;
}
}
void OnMouseDown()
{
if (Input.GetKeyDown(KeyCode.E))
{
if ( BreakGlass == true)
{
Destroy(gameObject);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612141508im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how do i make an object make itself and another object disapear when touched (2d game, 3d unity) 0 Answers
How can I make the Player be destroyed when I touch the end of the camera? 1 Answer
Collision with trigger is not working 1 Answer
Destroy instatiate object on trigger enter / collision,destroy instantiate prefab on trigger enter 0 Answers