I have made some code that, in my mind, should work, but it doesn’t work, here is the code
using UnityEngine;
public class Sign : MonoBehaviour
{
public GameObject textboxUI;
void OnCollisionEnter2D(Collision2D collisionInfo)
{
if (collisionInfo.collider.tag == "Player")
{
Debug.Log("Player, Hit e to read!");
if (Input.GetKey("e"))
{
Debug.Log("Player is reading");
textboxUI.SetActive(true);
if (Input.GetKey("q"))
{
Debug.Log("Player is done reading");
textboxUI.SetActive(false);
}
}
}
}
}
I can’t figure out why this won’t work, does the get key thing not work in the on collision enter?
1 Like
OnCollisionEnter/2D
only happens for a single physics frame. This code doesn’t loop so the inputs are never going to be hit within that single moment.
Input should be read in Update
. You can take advantage of the fact that Update doesn’t run when a component is inactive, and do something like this:
using UnityEngine;
public class Sign : MonoBehaviour
{
public GameObject textboxUI;
private void Awake()
{
this.enabled = false;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.E) == true)
{
textboxUI.SetActive(true);
}
else if (Input.GetKeyDown(KeyCode.Q) == true)
{
textboxUI.SetActive(false);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
this.enabled = true;
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
this.enabled = false;
textboxUI.SetActive(false);
}
}
}
1 Like
I think using OnCollisionStay2D would also be an option. Thouch using enabled of the script probably makes more sense, as it even allows testing without the player entering the trigger.
While this approach does work, in a more complex game you have to be careful to not ever have overlapping triggers. What I mean isn’t that triggers themselfs should not overlap, but that the player can not reach a position where he touches two or more such triggers at the same time. For such systems it usually makes more sense to have the interaction mechanic on the player who essentially picks an “IIneractable”. That way there can only be one active at a time. Though of course it depends on the game. In 3d games that’s even more important, though this seems to be a 2d game.
1 Like