I’m pretty new to Unity but figured I would give v6 a go since I like the improvements in some areas for performance, but I’m a little perplexed on “GetComponent” as it seems to behave different now in a MonoBehavior script.
Usage Scenario:
Assign the var "anim" the reference to the Animator component in Awake:
[SerializeField] private Animator anim;
private void Awake() {
anim = GetComponent<Animator>();
}
No compiler errors, always returns Null Reference. Only when I assign it manually in the inspector do these null references stop.
Background: I started a new project in Unity 6 (6000.0.32f1 LTS), tried the above code like I have on 20+ other scripts in the past, and I’m getting null references. These null references stopped after I manually assigned the component to anim in the inspector. Rest of the code was working fine after that.
Since it’s early I tested this:
Saved the project and closed it. Switched to 2022.3.16f1 LTS. Battled your usual headaches that come up when changing Editor versions (removing packages not avail in 2022, etc.). I made a single change in my scripts because “velocity” is actually velocity in 2022 (its depreciated in Unity 6 for linearVelocity), but nothing related to “GetComponent”, and it worked like always.
My machine: Brand new MSI laptop on Windows 11 (24H2 Build 26100.2605) (purchased Dec 22, 2024), fresh setup (no backed up data at all), new install of VS2022, new install of Unity 6 (and then 2022.3 after for testing in a known good environment). (if anyone says Bad Unity 6 install maybe Unity should remove it from LTS if the very first install I do of it gets corrupted - and the chances of the computer doing it is pretty slim - unity is the only thing “acting up” as end users put it)
The same method above is what I’ve done in 2019, 2020, 2022, 2023…and it worked but not U6.
I’ve read over the docs from the site and I’m still stumped:
Unity 6 GetComponent:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.GetComponent.html
Unity 2022.3 GetComponent:
https://docs.unity3d.com/2022.3/Documentation/ScriptReference/GameObject.GetComponent.html
Perhaps I’m missing something being a Unity n00b but should GetComponent not work the same across everything? Go easy on me
Mods: if this is in the wrong section please move it to the right one