- Home /
Script can't find Component within Start() - C#
Hi folks,
I'm trying to get another script `Script2` via `GetComponent()` within the `Start()` method of Script1
.
Unfortunately it return nothings at times and the script fails. I'm told that the variable isn't instantiated.
I tried moving the Script1
lower on the Component list of the GameObject
, but it still turns up problems at times.
Is this because when Start()
is called Script2
doesn't exist yet? Or something along those lines?
Really not sure what to do here.
If I understand correctly, the component you are looking at and the script calling GetComponent are attached to the same game object ?
Could you post your code please? We might be able to understand your problem a bit better!
I'm assu$$anonymous$$g that Script2 is on another game object? If so, how does that game object get created?
Answer by IgorAherne · Jul 22, 2013 at 02:29 PM
1) Create an empty GameObject. Name it _second
2) Drag Script 2 onto the _second in the hierarchy view
3) Create an empty GameObject. Name it _first
3)Drag Script 1 onto the _first in hierarchy
in Script1 declare a variable
var shortcutToScript2 : Script2;
4)In start() of Script 1 write:
function Start(){
shortcutToScript2 = GameObject.Find("_second").GetComponent(Script2);
}
//now whenever you want to reference Script2 (That particular instance in the gameObject _second) from Script1, simply use shortcutToScript2
//for example
function Update(){
shortcutToScript2.myVariableOfScript2++;
}
if you need to reference a component in the same game object, say you have both Script1 and Script2 on _first. Then you could create a shortcut to script2 from script1 like this:
shortcutToScript2 = this.GetComponent(Script2)
You should declare shortcutToScript2 outside any function, and assign to it at Start. If declared inside a function, the variable is temporary and will exist only while Start is executing.