GetComponent from one Instantiated prefab to the other

Hi, I’m Instantiating two prefabs into my scene

the first one is a capsule with a character collider on it

the second one is an empty game object with two child game objects with Joystick scripts attached

what I’m trying to do is: from the first one is find the joystick scripts on the second ones children by using …

private var moveJoystick : JoystickLeft;
private var rotateJoystick : JoystickRight;

function Start(){
	moveJoystick = GameObject.Find("leftJoystick").GetComponent(JoystickLeft);
	rotateJoystick = GameObject.Find("rightJoystick").GetComponent(JoystickRight);

But keep getting the error … NullReferenceException pointing at the first line in Start above, why? Is it because they get Instantiated one right after the other?

If you’re instantiating the objects with a separate script, which is what it looks like, try using a coroutine in Start() that waits to make sure both objects are found. They may not be both instantiating on the first frame, so give it a chance to catch up.

#pragma strict

private var moveJoystick;
private var rotateJoystick;
private var leftJoystick : GameObject;
private var rightJoystick : GameObject;
function Start()
	while(moveJoystick == null | rotateJoystick == null)
		if(GameObject.Find("leftJoystick") != null)
			moveJoystick = GameObject.Find("leftJoystick").GetComponent("JoystickLeft");
		if(GameObject.Find("rightJoystick") != null)
			rotateJoystick = GameObject.Find("rightJoystick").GetComponent("JoystickRight");
		yield WaitForEndOfFrame();

If you get NullReferenceException on the first line, then the problem must be


returning null. This indicates, that game object with name “leftJoystick” does not exist yet.

To correct this, I suggest changing the moveJoystick and rotateJoystick variables to public:

public var moveJoystick : JoystickLeft;
public var rotateJoystick : JoystickRight;

and just assigning these values in inspector (from your empty object children). Plus of course remove assigning from Start of capsule script.

EDIT: oops - just noticed the empty object is prefab as well. My method requires it to be an instance (available in scene hierarchy).