Hi, I’m having an issue with GetComponent. The object was working fine until I changed the 3d model child object. Now the script won’t find the animator Component it’s attached to. The animator and the script are on the same object. The object is disabled on start. the Debug.Log for the animator says null. I’m really stumped on this one. I even added the CoRoutine in case it was a race condition causing it.
No, not at all. Your posts even lists several of the most common ways to fail, which I also list a few more of below.
Remember: GetComponent doesn’t fail anymore than if you went looking for a thing in a location where that thing wasn’t present.
Keep in mind that using GetComponent() and its kin (in Children, in Parent, plural, etc) to try and tease out Components at runtime is definitely deep into super-duper-uber-crazy-Ninja advanced stuff.
Here’s the bare minimum of stuff you absolutely MUST keep track of if you insist on using these crazy Ninja methods:
what you’re looking for:
→ one particular thing?
→ many things?
where it might be located (what GameObject?)
where the Get/Find command will look:
→ on one GameObject? Which one? Do you have a reference to it?
→ on every GameObject?
→ on a subset of GameObjects?
what criteria must be met for something to be found (enabled, named, etc.)
If you are missing knowledge about even ONE of the things above, your call is likely to FAIL.
This sort of coding is to be avoided at all costs unless you know exactly what you are doing.
Botched attempts at using Get- and Find- are responsible for more crashes than useful code, IMNSHO.
If you run into an issue with any of these calls, start with the documentation to understand why.
There is a clear set of extremely-well-defined conditions required for each of these calls to work, as well as definitions of what will and will not be returned.
In the case of collections of Components, the order will NEVER be guaranteed, even if you happen to notice it is always in a particular order on your machine.
It is ALWAYS better to go The Unity Way™ and make dedicated public fields and drag in the references you want.