Here is my code:
private bool buttonPressed;
void Update()
{
buttonPressed = doorButton.GetComponent<Button>().buttonPressed;
if (buttonPressed)
{
doorOpened = true;
}
}
On the other script (Button), buttonPressed returns true when Input.GetButtonDown. That’s why buttonPressed returns true for a brief second and returns false immediately after.
I am quite sure buttonPressed returns true for a brief moment in my other script, however in the script above, buttonPressed always returns false.
I think button on click is not applicable to my game, because my game is a 3D game, where I used raycast to determine if player’s hand is in range of the button, if so, when player input button down, the bool buttonPressed will return true
Isn’t it a UI Button? Is it a in game object?
You can use this: GitHub - yigitkahraman/EventSystem: Event System for Unity.
There is no need for references etc. Copy EventSystem.cs to your scripts folder somewhere.
In button object, use: this.PostEvent("ButtonPressed")
In (I’m guessing it’s a door script) this script:
private void OnEnable(){
this.Subscribe("ButtonPressed", OpenDoor);
}
private void OnDisable(){
this.Unsubscribe("ButtonPressed", OpenDoor);
}
private void OpenDoor(object arguments){
openDoor = true; //or whatever you want when "ButtonPressed" event happens.
}
What we do here is, instead of checking every frame if buttonIsPressed, button notifies this script that buttonIsPressed.
No, button it not an UI button, it is a script that only has a bool in it, attached to the 3D gameObject. I am using the player controller script to change the status of the bool from false to true when button is pressed. The bool is then accessed by another script.
Here is the other script:
public GameObject button;
private Button buttonScript;
private bool buttonPressed;
void Start()
{
buttonScript = button.GetComponent<Button>();
}
void Update()
{
buttonPressed = buttonScript.buttonPressed;
if (buttonPressed)
{
Debug.Log("Button is pressed");
}
}
Strange thing is that the same script works on some objects but not on some other ones
I finally resolved the issue by deleting the components and adding them back in