- Home /
The question is answered, right answer was accepted
Showing UI image when inside a trigger and then pressing a button
So i want my player to move up to a sign on a wall with a trigger, which will then show the text "E to interact", that bit I worked out but i want an UI image to show up when my player is inside the trigger and presses E but i can't seem to detect the trigger and input at the same time.
[SerializeField] private Image instructImg;
private bool isTouching;
private void OnTriggerStay2D(Collider2D other)
{
if (Input.GetKeyDown("e"))
{
isTouching = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
isTouching = false;
}
private void Update()
{
if (isTouching)
{
instructImg.enabled = true;
}
else
{
instructImg.enabled = false;
}
}
This is all i got right now, I have tried a some other approaches but none of them seem to work. Would really appreciate some help with this, thank you.
Sorry but that didn't work, however after a few epithanies in a row I made it work so that the image only appears when my player is in the trigger and presses e and when he goes too far away or presses e again it just turns off again. With this code.
[SerializeField] private Image instructImg;
private bool isTouching;
private void OnTriggerStay2D(Collider2D other)
{
isTouching = true;
}
private void OnTriggerExit2D(Collider2D other)
{
isTouching = false;
}
private void Update()
{
if (isTouching && Input.Get$$anonymous$$eyDown("e"))
{
instructImg.enabled = !instructImg.enabled;
}
else if (!isTouching)
{
instructImg.enabled = false;
}
}
Answer by Priyanka-Rajwanshi · Jul 02, 2018 at 05:29 PM
@unity_qYQW964U5-CBQw Try this:
private void OnTriggerEnter2D(Collider2D other)
{
isTouching = true;
}
private void OnTriggerExit2D(Collider2D other)
{
isTouching = false;
}
private void Update()
{
if (isTouching && (Input.GetKeyDown(KeyCode.E)))
{
instructImg.enabled = true;
}
else
{
instructImg.enabled = false;
}
}
Thanks but I actually managed to figure it out like 2 $$anonymous$$utes ago.
Please accept the answer if it's the solution.
Answer by Epicepicness · Jul 02, 2018 at 05:57 PM
Is there a collider and a Rigidbody on the triggering object? I believe you need both of those in order for OnTriggerEnter and such to trigger properly. The following script worked for me:
using UnityEngine;
using UnityEngine.UI;
public class ShowImage : MonoBehaviour {
[SerializeField] private Image instructImg;
private void OnTriggerStay2D () {
if (Input.GetKeyDown ("e")) {
ToggleImage (true);
}
}
private void OnTriggerExit2D () {
ToggleImage (false);
}
private void ToggleImage (bool enable) {
if (instructImg.enabled != enable) {
instructImg.enabled = enable;
}
}
}
Practically the same thing, just without constant update checks.
Follow this Question
Related Questions
unity 2017 UI Delay bug 0 Answers
Script Repositions UI Element in the Wrong Spot 0 Answers
Shoot accuracy bar 1 Answer