Ive added this script to an npc in my 2d game, so whenever im inside a trigger box collider i right click and it opens his dialogue box. and it works, but not always. Sometimes i have to click 6 or 7 times, other times it works in 1 or 2. The rigidbody on both the player and the npc are set to never sleep as i read that was a fix but it didnt seem to totally fix it, here is the code for the script attached to the npc.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogieHolder : MonoBehaviour {
public string dialogue;
private DialogueManager dMan;
// Use this for initialization
void Start () {
dMan = FindObjectOfType<DialogueManager>();
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D(Collider2D other)
{
if(other.gameObject.name == "Player")
{
if(Input.GetKeyDown(KeyCode.Mouse1))
{
dMan.ShowBox(dialogue);
}
}
}
}
I have finally found a working fix for this, thanks everyone for your help.
public string dialogue;
private DialogueManager dMan;
private bool playerEnter;
// Use this for initialization
void Start()
{
dMan = FindObjectOfType<DialogueManager>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse1) && playerEnter)
{
dMan.ShowBox(dialogue);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
playerEnter = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
playerEnter = false;
}
}
}
this is better remove oncollisionstay2d
public LayerMask thingYouWantToDetectLayer;//select the layer of the thing you want to detect in editor
// Update is called once per frame
void Update() {
if (Input.GetMouseButtonDown(0)){
Collider2D wathYouWantToDetect = Physics2D.OverlapBox(transform.position, new Vector2(transform.localScale.x, transform.localScale.y), 0f, thingYouWantToDetectLayer);
if (wathYouWantToDetect.gameObject.name != “”)//checks if the colider isn’t empty
{
//youractions
}
}
}
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.name == “Player” && Input.GetKeyDown(KeyCode.Mouse1))
{
dMan.ShowBox(dialogue);
}
}
Inputs are updated at different intervals than the physics callbacks.
Consider moving the input detection to the Update method and storing the result locally.
This should give that better responsiveness feeling thingy.
From Unity Docs: Unity - Scripting API: Input
“Note also that the Input flags are not reset until “Update()”, so its suggested you make all the Input Calls in the Update Loop.”