Accessing prefab components

Given the following code:

GameObject myGameObject = GameObject.Find("instance3");
MyScript script = myGameObject.GetComponent<MyScript>();

The script variable is always null when myGameObject is a prefab I dragged into the scene, but fine when I make it from scratch my making a GameObject and adding the components manually.

If I click on instance3 in the scene and look at the inspector, I can see it definitely has a MyScript component, so why is it coming back as null?.

Am I using prefabs wrong, or have I fundamentally misunderstood what they are for?

Do you need to find a specific instance of a certain type of game object? Otherwise I would say use another function that will return the script directly (FindObjectOfType).

MyScript script = (MyScript)FindObjectOfType(typeof(MyScript));
// OR
MyScript script = (MyScript)FindObjectOfType<MyScript>();

Note: You need to cast, as this function only returns an “Object” type. Hope that helps.