Unity 2017 C#开发中GetComponent<Button>返回null问题排查求助
Hey there, let's work through why your GetComponent<Button>() call is returning null in your LevelLock script. This is a super common Unity gotcha, so here are the most likely fixes to check:
1. Verify Component Hierarchy & Script Placement
From your description, you mentioned a "Text object with a Button component attached"—but in Unity, it's far more standard to have a Button GameObject that contains a Text child object (for the button's label).
If your LevelLock script is mounted on the Text child instead of the parent Button GameObject, GetComponent<Button>() will return null because it only searches the current GameObject, not its parents or children.
Fixes here:
- Move the
LevelLockscript to the GameObject that has the Button component attached directly. - Or, if you need to keep the script on the Text object, use
GetComponentInParent<Button>()to search up the hierarchy:void Start () { lvlBtn = GetComponentInParent<Button>(); if (lvlBtn != null) { // Your logic here, e.g. disable the button if locked lvlBtn.interactable = !isLocked; } else { Debug.LogError("No Button component found on this object or its parent!"); } }
2. Double-Check the Button Component Exists
It sounds obvious, but sometimes we accidentally remove components or misassign objects. Open the Inspector for the GameObject your LevelLock is attached to and confirm:
- The Button component is clearly listed in the Inspector.
- If you're using
GetComponentInParent, make sure the parent GameObject actually has the Button component enabled.
3. Use Awake() Instead of Start() (Optional)
In Unity 2017, script execution order can occasionally cause Start() to run before the Button component is fully initialized (though this is rare). Try moving your component-fetching code to Awake(), which runs earlier in the initialization cycle:
private void Awake() { lvlBtn = GetComponent<Button>(); // or GetComponentInParent<Button>() if needed } void Start () { if (lvlBtn != null) { lvlBtn.interactable = !isLocked; } else { Debug.LogError("Button component not found!"); } }
4. Ensure the GameObject Isn't Destroyed Prematurely
If the GameObject with the Button component is being destroyed by another script before your LevelLock.Start() runs, GetComponent() will return null. Check for any Destroy() calls targeting that object in other scripts in your scene.
内容的提问来源于stack exchange,提问作者F_Bass

