- Home /
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 :-)
Many thanks!
Answer by hexagonius · Feb 12, 2015 at 11:10 AM
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>();
Your answer
Follow this Question
Related Questions
Changing game object based on variable state? 1 Answer
Instantianig a teleporter prefabs with destination variables 1 Answer
Passing a variable to the child of Instantiated object? 1 Answer
How to make reference from prefab to variable via C#/JavaScript? 1 Answer
Updating a variable on a script in an instanced object 1 Answer