How do I access a variable from another script that is in a prefab that isnt in the scene?

I need to access a damage variable in another script without making it public and dragging it over and dropping it. the variable is in a prefab that I made. normally if I want to access it while its apart of the game or in the scene, I would use

shipLaserDmg = GameObject.Find ("ShipLaser").GetComponent ().damage;

But, since its not in the scene, I just get

(NullReferenceException: Object reference not set to an instance of an object)

Ive heard of having to load the prefab using

(GameObject)Resources.Load ("/Prefabs/ShipLaser");

but I can’t get it working. Can anyone Help me out here? It would be nice if I didn’t have to go though all this just to do it(maybe there’s a way but Im still new to c#).

Keep in mind that in your example you are changing an instance of an object, not a prefab. Prefabs are more like classes, you then create actual objects by instantiating them.

That said, it is possible to affect a prefab’s variables, but that will affect all objects instantiated from this prefab in the future, and not any existing objects.

There are two ways to do this:

  1. add a reference to the prefab in your script, and then drag the prefab from the project (not the scene) to that reference in the inspector. Then you can access it through that reference.
  2. To use Resources.Load("MyObject");, the “MyObject” prefab has to be a in the project under a folder named “Resources”. It must be under that folder for it to be loadable at runtime through resources.load. You can add subfolder and then use Resources.Load("Subfolder/MyObject");