What should be the C# syntax for the condition if (This Button is interactable)?
I have a script attached to the button, Which has to run only if the button is interactable.
Thank you in advance!
What should be the C# syntax for the condition if (This Button is interactable)?
I have a script attached to the button, Which has to run only if the button is interactable.
Thank you in advance!
Once you have reference to a Button, you can use Button.interactable to determine if the button is interactable. interactable is a member of the UI.Selectable class; Button inherits from Selectable, and thus, has access to interactable.
The below script takes a Button reference, and runs logic if the button is selectable. When you intend to "run the script", simply call Run(). The logic will not run, if the Button is not interactable.
public Button button;
public void Awake()
{
if(button == null)
{
button = GetComponent<Button>();
}
}
public void Run()
{
if(button != null && button.interactable)
{
// run your logic, here.
}
}
Checking button.interactable checks only if the button itself is interactable, completely ignoring the possible existence of Canvas Groups.
The correct check should use IsInteractable() instead of interactable:
public Button button;
public void Awake()
{
if(button == null)
{
button = GetComponent<Button>();
}
}
public void Run()
{
if (button != null && button.IsInteractable())
{
// run your logic here.
}
}
IsInteractable() is a nicer way to access the bool, it still seems to go as well to check against interactable
\$\endgroup\$
m_GroupsAllowInteraction
\$\endgroup\$