- Home /
GetComponent doesn't work anymore
I've left off my game before christmas and wanted to pick up development right now, but it seems my scripts aren't working anymore...
To be more specific, i've got several C# scripts attachted to my player, of which one is disabled at the beginning and should be enabled, when the player's touching a rope.
I'll do that like this:
PlayerClimbing climbingScript;
void Start ()
{
climbingScript = (PlayerClimbing)gameObject.GetComponent("PlayerClimbing");
}
but when i try to access the climbingScript object, unity is throwing an "object reference not set to a instance of an object" error and the climbingScript is null.
I've also tried to get the Script via:
climbingScript = GetComponent("PlayerClimbing") as PlayerClimbing;
But that also doesn't work....
Can it be, that there's a bug in Unity ?! It seems that Unity has automatically updated itself, since i last used it...
Any help's highly appreciated !
Answer by Lovrenc · Jan 19, 2013 at 11:14 AM
Use
(PlayerClimbing)gameObject.GetComponent<PlayerClimbing>();
Answer by Talantyyr · Jan 19, 2013 at 11:44 AM
Thank you, it's working now !
Wow, that's strange. But, i swear, it has worked that way before...
I'm new to C#, and read
other = gameObject.GetComponent("ScriptName") as ScriptName;
in the documentation, so i thought it doesn't matter if i cast the class or use as... :)
Btw, why did
climbingScript = GetComponent("PlayerClimbing") as PlayerClimbing;
not work? That seems to be ok according to the documentation?
Use comments for commenting.
Rule 1: Never use strings for searching components. Use type version, it is faster.
The problem is not in casting, it is HOW you were looking for component. I guess your way is not working because you have your script dissabled and class name can not be found or something like that. Not really sure how the function is working.
Your answer
![](https://koobas.hobune.stream/wayback/20220613091213im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
GetComponent returns null reference 0 Answers
NullReference when calling a function to another script 2 Answers
access enum values 0 Answers
GetComponent not working C# 1 Answer
A simple CS0309 problem... 2 Answers