So as the title says, I am making a game that requires a door with a button to open and close it. I cant figure out how to script it so that it closes when you click the button again. Here’s the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorController : MonoBehaviour
{
public GameObject Door;
public bool doorIsOpening;
void Update()
{
if (doorIsOpening == true)
{
Door.transform.Translate(Vector3.up * Time.deltaTime * 800);
//if the bool is true open the door
}
if (Door.transform.position.y > 30f)
{
doorIsOpening = false;
//if the y of the door is > than 7 we want to stop the door
}
}
void OnMouseDown()
{ //THIS FUNCTION WILL DETECT THE MOUSE CLICK ON A COLLIDER,IN OUR CASE WILL DETECT THE CLICK ON THE BUTTON
doorIsOpening = true;
//if we click on the button door we must start to open
}
}
Please help me
Add a bool called buttonState. With false being the state you want the button to have for the first press and true being the state you want the button to have for the second press.
After doing the logic for whatever button press state is active at that time, do buttonState = !buttonState to invert it.
Okay, I’ll try that and send the code once I eat lunch, thanks!
Exactly what @pinksheep8426 said above, but also please format your code correctly.
Here are some extra notes on reporting issues here:
http://plbm.com/?p=220
@pinksheep8426
I added the stuff as you said and got this:
public class DoorController : MonoBehaviour
{
public GameObject Door;
public bool doorIsOpening;
public bool buttonState;
void Update()
{
if (doorIsOpening == true)
{
Door.transform.Translate(Vector3.up * Time.deltaTime * 800);
//if the bool is true open the door
}
if (Door.transform.position.y > 30f)
{
doorIsOpening = false;
//if the y of the door is > than 7 we want to stop the door
}
if (buttonState = false);
{
buttonState = !buttonState;
}
}
void OnMouseDown()
{ //THIS FUNCTION WILL DETECT THE MOUSE CLICK ON A COLLIDER,IN OUR CASE WILL DETECT THE CLICK ON THE BUTTON
doorIsOpening = true;
//if we click on the button door we must start to open
}
}
I don’t exactly know C# that well, so based on when I tried playing the code, it didn’t work, could you point out, or anyone else, where and what I did wrong? Thanks.