unity toggle点击事件切换事件绑定

unity3d自定义Toggle组件,解决设置isOn自动调用方法 - 简书
unity3d自定义Toggle组件,解决设置isOn自动调用方法
当我们在使用unity自带的Toggle组件的时候,我们是通过Toggle组件上的isOn属性得知是开启我们的功能面板还是关闭,这时候通常我们会给toggle绑定一个方法,当我们点击toggle的时候,调用方法,同时播放点击音效,可是有些时候,需要我们在切换界面的时候通过其它方法来关闭我们的属性isOn为false,方便我们下次点击的时候,isOn为true,这时候,我们单独对toggle的isOn属性赋值时会调用一次我们的方法,同时还会播放一次声音,恶心的事情就此发生,所以在项目中不得不重写了此组件,以方便项目中多处使用,下面是MyToggle脚本,挂载到对象身上即可,和unity自带的Toggle用法一样,只是在手动设置isOn属性的时候不会自动调用方法。
using UnityE
using UnityE
using UnityEngine.E
using UnityEngine.EventS
using UnityEngine.S
using UnityEngine.UI;
/// &summary&
/// 自定义Toggle组件
/// &/summary&
[RequireComponent(typeof(RectTransform))]
public class MyToggle : Selectable, IEventSystemHandler, IPointerClickHandler, ISubmitHandler, ICanvasElement
/// &summary&
/// toggle为true时切换显示的底图
/// &/summary&
public Graphic m_ChangeI
[SerializeField]
[FormerlySerializedAs("m_IsActive")]
private bool m_IsOn;
public MyToggle.ToggleTransition toggleTransition = MyToggle.ToggleTransition.F
public Toggle.ToggleEvent onValueChanged = new Toggle.ToggleEvent();
/// &summary&
/// 设置ison属性(自动调用一次方法)
/// &/summary&
public bool isOn
return this.m_IsOn;
this.Set(value);
/// &summary&
/// 设置ison属性(不会自动调用方法)
/// &/summary&
public bool IsOn
return this.m_IsOn;
this.Set(value, value, value);
protected MyToggle()
public virtual void Rebuild(CanvasUpdate executing)
if (executing != CanvasUpdate.Prelayout)
this.onValueChanged.Invoke(this.m_IsOn);
public virtual void LayoutComplete()
public virtual void GraphicUpdateComplete()
protected override void OnEnable()
base.OnEnable();
this.PlayEffect(true);
this.IsOn =
protected override void OnDisable()
base.OnDisable();
this.IsOn =
private void Set(bool value)
this.Set(value, true);
private void Set(bool value, bool sendCallback)
if (this.m_IsOn == value)
this.m_IsOn =
this.PlayEffect(this.toggleTransition == MyToggle.ToggleTransition.None);
if (!sendCallback)
this.onValueChanged.Invoke(this.m_IsOn);
private void Set(bool value, bool sendCallback, bool call)
if (this.m_IsOn == value)
this.m_IsOn =
this.PlayEffect(this.toggleTransition == MyToggle.ToggleTransition.None);
if (!sendCallback)
private void InternalToggle()
if (!this.IsActive() || !this.IsInteractable())
this.isOn = !this.isOn;
/// &summary&
/// 点击事件
/// &/summary&
/// &param name="eventData"&Current event.&/param&
public virtual void OnPointerClick(PointerEventData eventData)
if (eventData.button != PointerEventData.InputButton.Left)
this.InternalToggle();
public virtual void OnSubmit(BaseEventData eventData)
this.InternalToggle();
public enum ToggleTransition
[Serializable]
public class ToggleEvent : UnityEvent&bool&
protected override void OnDidApplyAnimationProperties()
if ((UnityEngine.Object)this.m_ChangeImage != (UnityEngine.Object)null)
bool flag = !Mathf.Approximately(this.m_ChangeImage.canvasRenderer.GetColor().a, 0.0f);
if (this.m_IsOn != flag)
this.m_IsOn =
this.Set(!flag);
base.OnDidApplyAnimationProperties();
private void PlayEffect(bool instant)
if ((UnityEngine.Object)this.m_ChangeImage == (UnityEngine.Object)null)
if (!Application.isPlaying)
this.m_ChangeImage.canvasRenderer.SetAlpha(!this.m_IsOn ? 0.0f : 1f);
this.m_ChangeImage.CrossFadeAlpha(!this.m_IsOn ? 0.0f : 1f, !instant ? 0.1f : 0.0f, true);
protected override void Start()
this.PlayEffect(true);
protected override void OnValidate()
base.OnValidate();
this.Set(this.m_IsOn, false);
this.PlayEffect(this.toggleTransition == MyToggle.ToggleTransition.None);
if (PrefabUtility.GetPrefabType((UnityEngine.Object)this) == PrefabType.Prefab || Application.isPlaying)
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild((ICanvasElement)this);
This article is a record of my journey to learn Game Development and it will keep updating. 由于这篇文章的长度早已超出了简书编辑器的限制,因此后续内容将不在本文中更新,请移步本人的独...
?开启? 【iAPP实现进入界面执行逐一显】 〖 15:22:14〗 《//首先开一个线程,因为你有这么多的stop要执行,其次必须使用ufusui(),否则可能不会显示你的字体。切记:文字必须设置“text=”,否则很尴尬,还有我这里的8,14是两个文...
111. [动画系统]如何将其他类型的动画转换成关键帧动画? 动画-&点缓存-&关键帧 112. [动画]Unity引擎Mecanim动画系统功能优点? 答: l 简单化对类人角色动画设计与功能实现的工作流程。 l Mecanim动画系统使用一个可视化编程工具来管理动画之间...
用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你能获得这些料: 知道setContentView()之后发生了什么? ... Android 获取 View 宽高的常用正确方式,避免为零 - 掘金 相信有很多...
用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金Cover 有什么料? 从这篇文章中你能获得这些料: 知道setContentView()之后发生了什么? ... Android 获取 View 宽高的常用正确方式,避免为零 - 掘金相信有很多朋友...
两种方法监测网络状态: AFNetworking中AFNetworkReachabilityManager监测网络状态 (void) inspectNetworkState {//创建网络状态监测管理者AFNetworkReachabilityManager manager...
舞枪灵湖畔,弹唱古亭边。 今朝逢佳日,福寿天际来。
《祝天下所有的情侣都是失散多年的兄妹》,第一次知道好妹妹乐队就是因为这首歌,随后听了些他们的翻唱,像是《青城山下白素贞》,《你到底有几个好妹妹》,《往事只能回味》等。后来知道,他们出了第一张专辑《春生》,备受好评,吸引了一批粉丝,到第二张《南北》时却被骂,说风格跟第一张雷同...unity 5.4.1f1 版本设置IsOn属性不能改变Toggle组件的状态_unity吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:28,965贴子:
unity 5.4.1f1 版本设置IsOn属性不能改变Toggle组件的状态收藏
如题,用了5.4.1f1后,无论勾选还是不勾选IsOn属性Toggle组件都没有反应,按理说不勾选的话,勾子应该隐藏的呢,可是并没有。于是我在5.3版本里一看,设置IsOn属性却是能立马看到勾子变化的,这个是5.4.1f1版本的bug吗?
来这里在线学习Unity!
LZ我5.6也发现了这个问题,之前都可以使用正常一次异常后就都是错误了
LZ你有什么解决方法吗?
2017版躺枪,找不到解决办法
要运行起来点击才能看到变化,不运行改是没反应的了
登录百度帐号Version: 2018.2 (switch to
or )LanguageEnglishC#class in
UnityEngine.UI/Inherits from:Other VersionsImplements interfaces:, , , Success!Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.Submission failedFor some reason your suggested change could not be submitted. Please &a&try again&/a& in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.Your nameYour emailSuggestion*Submit suggestionDescriptionA standard toggle that has an on / off state.The toggle component is a
that controls a child graphic which displays the on / off state.When a toggle event occurs a callback is sent to any registered listeners of .Properties
Graphic affected by the toggle.
Group the toggle belongs to.
Return or set whether the Toggle is on or not.
Callback executed when the value of the toggle is changed.
Transition mode for the toggle.
Public Methods
See ICanvasElement.GraphicUpdateComplete.
See ICanvasElement.LayoutComplete.
Handling for when the toggle is 'clicked'.
Handling for when the submit key is pressed.
Handling for when the canvas is rebuilt.
Protected Methods
See MonoBehaviour.OnDisable.
Inherited Members
Static Properties
List of all the selectable objects currently active in the scene.
Properties
Enabled Behaviours are Updated, disabled Behaviours are not.
Has the Behaviour had enabled called.
The game object this component is attached to. A component is always attached to a game object.
The tag of this game object.
The Transform attached to this GameObject.
Allow a specific instance of a MonoBehaviour to run in edit mode (only available in the editor).
Disabling this lets you skip the GUI layout phase.
Should the object be hidden, saved with the scene or modifiable by the user?
The name of the object.
The AnimationTriggers for this selectable object.
Convenience function to get the Animator component on the GameObject.
The ColorBlock for this selectable object.
Convenience function that converts the referenced Graphic to a Image, if possible.
Use to enable or disable the ability to select a selectable UI element (for example, a Button).
The Navigation setting for this selectable object.
The SpriteState for this selectable object.
Graphic that will be transitioned upon.
The type of transition that will be applied to the targetGraphic when the state changes.
Public Methods
Calls the method named methodName on every MonoBehaviour in this game object or any of its children.
Is this game object tagged with tag ?
Returns the component of Type type if the game object has one attached, null if it doesn't.
Returns the component of Type type in the GameObject or any of its children using depth first search.
Returns the component of Type type in the GameObject or any of its parents.
Returns all components of Type type in the GameObject.
Returns all components of Type type in the GameObject or any of its children.
Returns all components of Type type in the GameObject or any of its parents.
Calls the method named methodName on every MonoBehaviour in this game object.
Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.
Cancels all Invoke calls on this MonoBehaviour.
Invokes the method methodName in time seconds.
Invokes the method methodName in time seconds, then repeatedly every repeatRate seconds.
Is any invoke on methodName pending?
Starts a coroutine.
Stops all coroutines running on this behaviour.
Stops the first coroutine named methodName, or the coroutine stored in routine running on this behaviour.
Returns the instance id of the object.
Returns the name of the GameObject.
Finds the selectable object next to this one.
Find the selectable object below this one.
Find the selectable object to the left of this one.
Find the selectable object to the right of this one.
Find the selectable object above this one.
UI.Selectable.IsInteractable.
Unset selection and transition to appropriate state.
Determine in which of the 4 move directions the next selectable object should be found.
Evaluate current state and transition to pressed state.
Evaluate current state and transition to appropriate state.
Evaluate current state and transition to normal state.
Evaluate eventData and transition to appropriate state.
Set selection and transition to appropriate state.
Selects this Selectable.
Returns true if the GameObject and the Component are active.
Returns true if the native representation of the behaviour has been destroyed.
Protected Methods
Transition the Selectable to the entered state.
Clear any internal state from the Selectable (used when disabling).
Returns whether the selectable is currently 'highlighted' or not.
Whether the current selectable is being pressed.
Internally update the selection state of the Selectable.
See MonoBehaviour.Awake.
See MonoBehaviour.OnBeforeTransformParentChanged.
See MonoBehaviour.OnCanvasGroupChanged.
Called when the state of the parent Canvas is changed.
See MonoBehaviour.OnDestroy.
See LayoutGroup.OnDidApplyAnimationProperties.
See MonoBehaviour.OnEnable.
This callback is called if an associated RectTransform has its dimensions changed.
See MonoBehaviour.OnRectTransformParentChanged.
See MonoBehaviour.OnValidate.
See MonoBehaviour.Reset.
See MonoBehaviour.Start.
Static Methods
Logs message to the Unity Console (identical to Debug.Log).
Removes a gameobject, component or asset.
Destroys the object obj immediately. You are strongly recommended to use Destroy instead.
Makes the object target not be destroyed automatically when loading a new scene.
Returns the first active loaded object of Type type.
Returns a list of all active loaded objects of Type type.
Clones the object original and returns the clone.
Does the object exist?
Compares if two objects refer to a different object.
Compares two object references to see if they refer to the same object.
Awake is called when the script instance is being loaded.
This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
LateUpdate is called every frame, if the Behaviour is enabled.
Callback for setting up animation IK (inverse kinematics).
Callback for processing animation movements for modifying root motion.
Sent to all GameObjects when the player gets or loses focus.
Sent to all GameObjects when the application pauses.
Sent to all game objects before the application is quit.
If OnAudioFilterRead is implemented, Unity will insert a custom filter into the audio DSP chain.
OnBecameInvisible is called when the renderer is no longer visible by any camera.
OnBecameVisible is called when the renderer became visible by any camera.
OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.
Sent when an incoming collider makes contact with this object's collider (2D physics only).
OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.
Sent when a collider on another object stops touching this object's collider (2D physics only).
:ref::OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.
Sent each frame where a collider on another object is touching this object's collider (2D physics only).
Called on the client when you have successfully connected to a server.
OnControllerColliderHit is called when the controller hits a collider while performing a Move.
Destroying the attached Behaviour will result in the game or scene receiving OnDestroy.
Called on the client when the connection was lost or you disconnected from the server.
Implement OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn.
Implement OnDrawGizmosSelected to draw a gizmo if the object is selected.
This function is called when the object becomes enabled and active.
Called on the client when a connection attempt fails for some reason.
Called on clients or servers when there is a problem connecting to the MasterServer.
OnGUI is called for rendering and handling GUI events.
Called when a joint attached to the same game object broke.
Called when a Joint2D attached to the same game object breaks.
Called on clients or servers when reporting events from the MasterServer.
OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse.
Called when the mouse enters the GUIElement or Collider.
Called when the mouse is not any longer over the GUIElement or Collider.
Called every frame while the mouse is over the GUIElement or Collider.
OnMouseUp is called when the user has released the mouse button.
OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed.
Called on objects which have been network instantiated with Network.Instantiate.
OnParticleCollision is called when a particle hits a Collider.
OnParticleTrigger is called when any particles in a particle system meet the conditions in the trigger module.
Called on the server whenever a new player has successfully connected.
Called on the server whenever a player disconnected from the server.
OnPostRender is called after a camera finished rendering the scene.
OnPreCull is called before a camera culls the scene.
OnPreRender is called before a camera starts rendering the scene.
OnRenderImage is called after all rendering is complete to render image.
OnRenderObject is called after camera has rendered the scene.
Used to customize synchronization of variables in a script watched by a network view.
Called on the server whenever a Network.InitializeServer was invoked and has completed.
This function is called when the list of children of the transform of the GameObject has changed.
This function is called when the parent property of the transform of the GameObject has changed.
OnTriggerEnter is called when the Collider other enters the trigger.
Sent when another object enters a trigger collider attached to this object (2D physics only).
OnTriggerExit is called when the Collider other has stopped touching the trigger.
Sent when another object leaves a trigger collider attached to this object (2D physics only).
OnTriggerStay is called once per physics update for every Collider other that is touching the trigger.
Sent each frame where another object is within a trigger collider attached to this object (2D physics only).
This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).
OnWillRenderObject is called for each camera if the object is visible and not a UI element.
Reset to default values.
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.
Update is called every frame, if the MonoBehaviour is enabled.
Did you find this page useful? Please give it a rating:UIToggle:切换,从名字就能知道这个组件能做什么。这个组件有两种状态ON/OFF.可以用于创建checkboxes, tabs, radio button groups。
效果展示:
一:使用步骤&&创建一个checkboxes
  1.首先在UI Root下建立一个Sprite,设置一张贴图,当作按钮的背景。
  然后为其添加碰撞组件和Toggle组件
  2.为第一个Sprite建立一个子Sprite,设置一张图片,当作选中的标识。
  将其调整到适当的位置。
  3.选择第一个Sprite的UIToggle组件
  为State Transition中的Sprite设置对象,即刚才添加的子Sprite。
以上便创建了一个checkboxes。
二:创建一个radio button groups
  1.将上面创建的checkboxes复制3个。
  2.将他们三个的UIToggle中的Group属性,都改为同一个数字,但不能是0。
  注意:UIToggle中的Starting State如果勾选的话初始状态则为选择状态。
三:监听UIToggle属性的变化
  定义一个脚本CheckBox_Test,创建一个方法isActive,
  然后将这个脚本添加到下面,并选择刚才定义的方法。
四:UIToggledObjects使用
  这个组件可以实现Tab切换的效果。
  1.接着上面的项目,在CheckBox下面创建两个Sprite
  2.为checkbox添加UIToggledObjects组件
  其中Activate表示激活状态下显示的组件,Deactivate表示激活状态下隐藏的组件。
  设置如下:
  其中两个Sprite,是不同的两个Sprite,即刚才创建的那两个。
  效果如下:
  源码地址如下:
  项目结构如下:
阅读(...) 评论()}

我要回帖

更多关于 unitytoggle点击事件 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信