How to find a prefab via script at RunTime?

Suppose in my game I will Instantiate some prefabs. And every time I instatiate a Prefab it will be random and will destroyed after few seconds. That means I cannot assign my prefabVariable from the editor

// my prefabVariable that i want to assign 
// different prefabs at different time via script
// as opposed to drag-dropping GameObjects in
// the editor
var variableForPrefab :GameObject;

function Start()
{
    // for finding a game object we could do 
    // variableForPrefab = GameObject.Find("GameObjectName");

    // if we want to find prefab like this, how can I do this??
}

PS: 1. how to do so randomly is NOT my concern
2. I want to know how to find a prefab via script at Run Time

An alternative solution to the one Leuthil mentioned is to put your prefabs into a special folder called Resources. Once they in there you can use Resources.Load to get the reference to the desired prefab. The path is relative to the resources folder. So imagine you have this setup:

"/Assets/resources/prefabs/prefab1.prefab"

You could load that prefab by using:

// UnityScript
variableForPrefab = Resources.Load("prefabs/prefab1", GameObject) as GameObject;

// C#
variableForPrefab = (GameObject)Resources.Load("prefabs/prefab1", typeof(GameObject));

While this works and seems to be quite useful it has some drawbacks:

  • It’s of course slower than linking the prefabs in the inspector since the method has to search at runtime for the resource.
  • Everything inside the Resources folders are included in the build, no matter if you actually use it somewhere. Unity can’t determine what is needed and what isn’t.

So Leuthil’s solution is the recommended one.

You can create an array and put each prefab you want to randomly choose from in that array. Then you will be able to drag-and-drop all of the prefabs into that array.