- Home /
GetComponent searches an objects child instead of the object
First, I have a gameobject that is named "Player1". It has a child, specifically used for checking things that touch it's feet.
For some reason, Unity is complaining when I try to set Player1's SpriteRenderer, saying that feetCheck has no SpriteRenderer. It seems that Unity thinks basePlayer1 is feet check, even though it's properly assigned. Could someone explain what's going on?
Here is my Player1:
The piece of code that is breaking is here:
And here is the error:
Here is the assignment in the inspector, showing that basePlayer1 is NOT feet check, and is assigned appropriately:
Finally, this is when I Debug.Log basePlayer1. Clearly, Player1 is the object, and yet when I print the object, it thinks it is feetcheck.
Any advice is appreciated :)
Answer by Bunny83 · Oct 20, 2014 at 12:31 AM
"Could someone explain what's going on?"
Sure, you probably did something wrong ;)
Unity never "thinks" anything. If basePlayer1 references the FeetCheck Gamobject when you use it (either your getcomponent line or the Devug.Log line) then it does reference this object. That's a matter of fact, no guessing needed. If it points to you player object at edit time but to something else at runtime, you probably set it to something else somewhere in your code.
You only showed some fragments, but i guess the script you're talking about is attached to the FeetCheck object, right? Also is your player object a prefab? Where have you assigned which "Player" to which variable on which object? It looks like you tried to hide as much as possible, however that doesn't help to even understand half of your actual setup.
Unity has biased opinions on what Player1 should be, and I'm merely trying to convince Unity to see things my way. All of this "logic" stuff you're throwing at me is confusing.
The script I'm talking about is not attached to FeetCheck, it is a script in an empty gameObject all on it's own to handle global variables.
$$anonymous$$y player object is a prefab, yes.
The player is assigned in the global handler script, not with code but with Drag n' Drop in the inspector. The second to last, and last picture shows this, on the right.
I'm not sure what you mean by trying to hide as much as possible, I'm completely willing to post more information/code. I posted everything that I thought was relevant, which, since I'm asking the question, I know doesn't help much :)
Answer by EClancy · Oct 20, 2014 at 06:16 PM
Figured this out on my own, but the answer is less glamorous than I would have thought. Upon exiting Unity last night, it crashed. Reopening it this morning caused another crash, and finally when it was working again, my variables were not properly assigned in the inspector. I reassigned them, and viola, it was working.
Turns out, the whole time Unity was just bugging and needed to get a few crashes out of it's system. Happens to the best of us.