如何通过Tab按键切换GameObject/组件的SetActive激活状态?
Toggle ObjectOne's Active State with Tab Key in Unity
Got it, let's adjust your code so pressing Tab switches ObjectOne between active and inactive states instead of just enabling it every time.
First, let's go over the issues in your original code:
- You’re always setting
SetActive(true)when Tab is pressed, so there’s no toggle behavior—pressing Tab multiple times just keeps it active. - There’s a missing semicolon after
ObjectOne.SetActive(true)which will throw a compile error.
Here’s the fixed code that implements the toggle functionality:
void Update () { if(Input.GetKeyDown(KeyCode.Tab)) { // Flip the active state: set to the opposite of the current state ObjectOne.SetActive(!ObjectOne.activeSelf); Debug.Log("Toggled ObjectOne state to: " + ObjectOne.activeSelf); } Debug.Log ("Update is called"); }
What changed?
- Instead of hardcoding
true, we use!ObjectOne.activeSelf—this grabs the opposite of the object’s current active state. If it was active, it becomes inactive, and vice versa. - Added the missing semicolon to fix the syntax error.
- Updated the Debug log to show the new state (optional, but super helpful for testing if the toggle is working as expected).
Quick reminder:
Make sure ObjectOne is properly assigned in the Unity Inspector (drag the object from your Hierarchy into the public field on your script component), otherwise you’ll get a NullReferenceException when pressing Tab.
内容的提问来源于stack exchange,提问作者Vojislav Dabic
相关产品推荐
相关产品推荐

