Hey guys,
I have a situation in my game in which a button needs to be pressed to open a door.
For the button, the actual button object and the base are parented under an empty gameobject called ButtonParent, to which the following script is attached:
using UnityEngine;
using System.Collections;
public class ButtonScript : MonoBehaviour
{
Animator animator;
public bool buttonDown;
public bool buttonInRange;
void Start()
{
buttonDown = false;
animator = GetComponent<Animator>();
}
void Update()
{
if (Input.GetButtonDown("Jump") && buttonInRange)
{
if (!buttonDown)
{
ButtonControl("Open");
buttonDown = true;
}
else
{
ButtonControl("Close");
buttonDown = false;
}
}
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")
{
buttonInRange = true;
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "Player")
{
buttonInRange = false;
}
}
void ButtonControl(string direction)
{
animator.SetTrigger(direction);
}
}
For the door, the two door objects are parented under an empty gameobject called DoorParent, to which the following script is attached:
using UnityEngine;
using System.Collections;
public class Doors : MonoBehaviour
{
public ButtonScript refButtonScript;
Animator animator;
bool doorOpen;
void Start()
{
doorOpen = false;
animator = GetComponent<Animator>();
refButtonScript = FindObjectOfType<ButtonScript>();
}
void Update()
{
if (refButtonScript.buttonDown == true)
{
DoorControl("Open");
doorOpen = true;
Debug.Log("Door should be open");
}
if (refButtonScript.buttonDown == false)
{
DoorControl("Close");
doorOpen = false;
Debug.Log("Door should be closed");
}
}
void DoorControl(string direction)
{
animator.SetTrigger(direction);
}
}
What’s supposed to happen is, when the player is within reach of the button, pressing space pushes the button, causing the bool buttonDown to be true, which is then called from the door script to open the doors.
I got it to work, almost.
When the button is pressed, the doors open, but then they close and open again. Likewise, when the button is pressed again, the doors close, and then open and close again.
I can’t figure out for the life of me why the doors are opening and closing twice. Can anyone tell what is going wrong?
Thanks.