- Home /
GetComponent null reference C#
I have 2 scripts attached to a cube I'm trying to get variables from the other script,but it always comes up null. in the start function of the script , physics, I have
void Start () {
script = transform.parent.GetComponent<Movement>();
}
The MonoScript editor suggests Class Movement , but when I run it I get a null reference exception. Then I can not use any of Movement's variables.
oops forgot to mention that this was in C#.
twisted's suggestion let's me access the variables in the editor, but when I actually run Unity it still throws an error.
Thanks thought I had use parent , when I didn't.
This worked
Movement script;
// Use this for initialization
void Start () {
script = GetComponent<Movement>() as Movement;
}
$$anonymous$$ovement script = ($$anonymous$$ovement) transform.parent.GetComponent<$$anonymous$$ovement>() as $$anonymous$$ovement;
ehh, try this.
The two scripts seem to be attached to the same component. So why do you try to get the component from the parent?
Try this:
script = GetComponent<$$anonymous$$ovement>();
@tw1st3d. Your line doesn't make much sense. Why do you cast the result of GetComponent 3 times? (as-cast inside the generic function, explicit as cast and explicit c-style cast). One time is more than enough.
I bet your if-statements look like this:
if (A==1 && 1==A && A==1)
Just to be sure A is 1 :P
@Bunny83: Typecast it from orbit. It's the only way to be sure.
Answer by Rahazan · Oct 04, 2013 at 01:57 AM
void Start() {
script = GetComponent<Movement>();
}
The Movement script is probably attached to the same GameObject as the Physics script, and not the parent GameObject (higher in the hierarchy).