prefabs not loading script reference via getComponent

I’m new to Unity. Based on the book I’m learning from, I have the following code to place a reference to an object’s script into a variable…

using UnityEngine;
using System.Collections;

public class ElectronScript : MonoBehaviour {
    public GameControlScript control; 

void Start () {
    control = GetComponent<GameControlScript>();
}

This works just fine as long as I manually drag the “GameControl” object (which contains the GameControlScript) into the ElecrtonScript’s placeholder reference for “control” within the editor.

However, when the Electron object (containing the ElectronScript) is used as a prefab, the prefab object is instantiated WITHOUT the reference in place (and does not load it from the GetComponent line) and thus nothing works.

I’m positive I’m simply doing this wrong, but can’t find any reference to the RIGHT way to do this :slight_smile:

Many thanks!


GetComponent alone is looking for the script on the GameObject the script is attached to. Since you’re cross referencing to another GameObject you need to find that and look there:

control = GameObject.Find("GameControl").GetComponent<GameControlScript>();