- Home /
How can I make this button's interactability be toggled on and off?
In this script, at the bottom, I am trying to make it so that once you gain 8 points, the button can be used to get to the next scene. Can someone please help me fix this script? Here is the script: using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float speed;
public Text countText;
public Text winText;
public Text nextLevel;
public Text levelName;
public Button PlayButton;
public void LoadByIndex(int sceneIndex)
{
SceneManager.LoadScene (sceneIndex);
}
private Rigidbody rb;
private int count;
void Start ()
{
rb = GetComponent<Rigidbody> ();
count = 0;
SetCountText ();
winText.text = "";
nextLevel.text = "";
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
}
}
void SetCountText ()
{
countText.text = "" + count.ToString ();
if (count >= 8)
{
winText.text = "You win!";
nextLevel.text = "Next Level";
PlayButton.GetComponent<PlayButton>().interactable = true;
}
else
{
PlayButton.GetComponent<PlayButton>().interactable = false;
}
}
}
Answer by Piyush_Pandey · Jun 16, 2017 at 07:16 AM
You wrote PlayButton.GetComponent<PlayButton>().interactable = true;
Use instead
void SetCountText ()
{
countText.text = "" + count.ToString ();
if (count >= 8)
{
winText.text = "You win!";
nextLevel.text = "Next Level";
PlayButton.interactable = true;
}
else
{
PlayButton.interactable = false;
}
}
}
This because your PlayButton
is of type Button
which contains the interactable
flag. This is the way to access Unity built in flag of interactable from its built in Button script.
I dont know if you have a child attached to it with a script name PlayButton
with a custom flag name interactable
. If that is the case then please give some more details.