Reputation: 13
Hello I'm creating a 2d game and have implemented a dialogue script - When one gameObject collides with another and a specific Key on the keyboard is pressed a text box appears.
The dialogue (text boxes) appears using OnGUI with an array method behind it. This works successfully. Once the dialogue has finished the array resets, However I would then think by everything already being true i.e. the collision and with the key pressed on the keyboard that the dialogue would appear again.. it doesn't.
The only way for me to allow the dialogue to reappear again is if my gameObject moves away from the other gameObject's collider and then collides again with it. Is there anyway for me to not have to move away from the collider and then have to reinitiate contact with a collision for my dialogue to show? I don't understand why I have to if all arguments are true?
Sorry if I've described my problem poorly, I hope somebody can help.. it's possible that this is the only way OnCollision2d works.. I don't know.
Here is my code I'm using C# (I'm not sure a specific part would be substantial enough, so I'll post it all) :
using UnityEngine;
using System.Collections;
public class showtext : MonoBehaviour
{
bool CollisionWithHouse = false;
bool ActionButtonTextAppearsWithCollision = false;
public string[] dialogue = {"Greetings?",
"Farewell, my friend."};
int index = 0;
Rect dialogueRect = new Rect(435,100,500,50);
Rect dialogueRect2 = new Rect(335,50,300,34);
void Update() {
if (CollisionWithHouse && (ActionButtonTextAppearsWithCollision && Input.GetKeyDown("r")))
{
index++;
}
if (CollisionWithHouse && Input.GetKeyDown("r")){
ActionButtonTextAppearsWithCollision = true;
}
}
void OnCollisionEnter2D(Collision2D house){
{
CollisionWithHouse = true;
}
}
void OnCollisionExit2D(Collision2D house){
CollisionWithHouse = false;
ActionButtonTextAppearsWithCollision = false;
}
void OnGUI() {
if (index < 1 && (CollisionWithHouse) && (ActionButtonTextAppearsWithCollision)) {
GUI.Box(dialogueRect, dialogue[index]);
}
if (index > 0 && (CollisionWithHouse) && (ActionButtonTextAppearsWithCollision)) {
GUI.Box (dialogueRect2, dialogue [index]);
}
else {
System.Array.Clear(dialogue,0, index = 0);
}
}
}
Thanks.
Upvotes: 1
Views: 430
Reputation: 2515
OnCollisionEnter only fires once when the collision occurs. If you want it to fire constantly while the objects are touching, you need to use a different check, like OnCollisionStay.
FROM COMMENTS
The value index
will never be reset while the two objects are touching. Check for the value of index you want (when the last item of dialogue
is used) and when that's matched, reset it to 0. That way, the dialogue can be restarted right away.
Upvotes: 1