Hello Guest

Author Topic: How to set state of Toggle button in code? (AS)  (Read 4830 times)

hawken

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 13
  • developer
    • View Profile
    • hawkenking
How to set state of Toggle button in code? (AS)
« 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.

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: How to set state of Toggle button in code? (AS)
« Reply #1 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.

hawken

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 13
  • developer
    • View Profile
    • hawkenking
Re: How to set state of Toggle button in code? (AS)
« Reply #2 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?

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: How to set state of Toggle button in code? (AS)
« Reply #3 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;

hawken

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 13
  • developer
    • View Profile
    • hawkenking
Re: How to set state of Toggle button in code? (AS)
« Reply #4 on: March 25, 2014, 04:46:46 am »
Thanks!