Hi all,
I created a really simple C# dialogue script where my player enters a 2D Box Collider and a text prompt “Press F Key…” appears. When they press the key, an image is displayed in the UI and the “Press F” prompt disappears. When the player leaves the 2D Box Collider, the image disappears. The action is repeatable. I dropped the script onto the box collider itself.
My script was actually working as expected–until I tried to add a second image that would be displayed instead of the first if an additional condition was met (in this case, the script was checking against a boolean from my player’s inventory script).
It didn’t work, which is fine, but after I removed the new code, the original code no longer works. The image no longer appears in the UI, and I’m getting NullReferenceExceptions on the “characterResponse.enabled” lines within Update. The “Press F” text prompt still appears and disappears perfectly.
This makes me pretty certain my original code was probably off and should be rewritten properly, so that’s all I’m looking to do. It’s just that I can’t figure out what I did wrong.
The original text and image to be displayed are both still tied into the public enterText and characterResponse fields in the inspector, so I don’t think that’s the issue.
Anyone have any ideas? Apologies in advance if the code is messy; I’m still learning:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.SceneManagement;
public class speak2 : MonoBehaviour
{
public Text enterText;
public Image characterResponse;
bool inBox = false;
bool talked = false;
void Update()
{
bool keyPressed = Input.GetKeyDown(KeyCode.F);
if (keyPressed && inBox)
{
enterText.text = "";
characterResponse.enabled = true;
talked = true;
}
else if (talked)
{
enterText.text = "";
characterResponse.enabled = true;
}
else if (inBox && !talked)
{
enterText.text = "PRESS F TO TALK";
characterResponse.enabled = false;
}
else if (!inBox && !talked)
{
characterResponse.enabled = false;
}
}
private void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.CompareTag("talk"))
{
inBox = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
enterText.text = " ";
inBox = false;
talked = false;
characterResponse.enabled = false;
}