2D Toolkit Forum

2D Toolkit => Support => Topic started by: hawken on January 21, 2014, 08:32:29 am

Title: How to set state of Toggle button in code? (AS)
Post by: hawken on January 21, 2014, 08:32:29 am
I'm making a setting that is persistent through scenes and need a toggle button to be on when the user loads that scene.

From the documentation it's not entirely clear how to do this without any examples.

I tried the follow code:

var myToggleButton : GameObject;

Code: [Select]
function Start() {
if (PlayerPrefs.GetInt("ButtonOn") == 1) {
tk2dUIBaseItemControl.ChangeGameObjectActiveState(myToggleButton, true);
}
}

But unsure if this is the way to do it. It's not really clear. I just want the Toggle Button to be on, using code. Thanks.
Title: Re: How to set state of Toggle button in code? (AS)
Post by: unikronsoftware on January 21, 2014, 11:47:17 am
Check the UI sample scenes, all of them bind buttons.
The gist of it - you have 2 options.

1. If you want to do it from code,
Code: [Select]
var myToggleButton : tk2dUIItem;
function OnEnable() {
   myToggleButton.OnDown += ButtonDown;
}

function OnDisable() {
   myToggleButton.OnDown -= ButtonDown;
}

function ButtonDown() {
  Debug.Log("Button pressed");
}

2. If you want to do it from the UI, drag your controller behaviour into the "Send Message.Target" slot on the button. (eg. 3D UI sample, button in the hierarchy). You then select ButtonDown on the OnClick message. You get the same result as above, without having to write any code. Its just preference which way you want to work with this.
Title: Re: How to set state of Toggle button in code? (AS)
Post by: hawken on January 30, 2014, 12:04:42 pm
Thanks for the feedback. Not really grasping it though :(

So basically I should show and hide the toggle states based on the setting I'm saving with playerPrefs?
Title: Re: How to set state of Toggle button in code? (AS)
Post by: unikronsoftware on January 30, 2014, 12:31:58 pm
I think I may have misunderstood your original question.
You'll still need to do this, and drag in a reference in your inspector.
var myToggleButton : tk2dUIToggleButton;

Then you'd drag the toggle button in the inspector.
After that you can do stuff like this.
myToggleButton.IsOn = PlayerPrefs.GetInt("ButtonOn") == 1;
Title: Re: How to set state of Toggle button in code? (AS)
Post by: hawken on March 25, 2014, 04:46:46 am
Thanks!