I am new to unity and I would like to understand how to make to appear an image when I enter to the trigger, and that when I exit to the trigger the image disappears.
I tried to write this. Did I do something wrong? because this does not work. The image of the canvas always remains.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SeeObjectWhenEnterInTrigger : MonoBehaviour
{
[SerializeField] private Image customimage;
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
customimage.enabled = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
customimage.enabled = false;
}
}
}
Looks fine. Standard questions:
-
Are you sure you’ve actually attached
this to an object?
-
Are you sure the object this is
attached to also has a Collider
attached set to IsTrigger?
-
Are you sure you’ve assigned the
image reference in the inspector and
it’s not throwing errors when trying
to change it’s Enabled status?
-
Are you sure the player object
actually has its tag set to “Player”?
-
Are you sure the player object has a
CharacterController or a rigidbody
AND collider attached, to be able to
activate triggers?
-
Are you sure that the layer this
object is on, and the layer the
Player object is on, are capable of
colliding with one-another (check the
Edit → Project Settings → Physics → Layer Collision Matrix)?
-
Are you sure that the GameObject the
image is on isn’t disabled, or that’s
the canvas parent isn’t disabled?
-
Are you sure that it isn’t actually
working, but the image is out of
range of the camera, or that it’s not
visible to that camera specifically
(on a layer not rendered by that
camera)?
Lots and lots of things that this could be. Throw a Debug.Log check into the TriggerEnter/Exit functions to see if they’re firing, and then go through the possibilities I’ve listed one by one based on whether it isn’t getting that far (a problem with layers or colliders), or if it’s getting that far and not mattering (a problem with the canvas / image object).