Referencing a specific object?

Hello. This may be a simple question, but normally, when you want to reference another object in a script, you set it as a variable. Is there a way to do reference the specific object without using a variable?

So that instead of this

var Bomb : GameObject;

if( Input.GetButtonDown( "Fire1" ) ){
        {Instantiate(Bomb, transform.position, transform.rotation);}


It would be this

if(Input.GetButtonDown( "Fire1" ) ){
{Instantiate(GameObject.Bomb, transform.position, transform.rotation);}


you could do

var bombPrefab = gameObject.FindWithTag("Bomb");
Instantiate(bombPrefab, transform.position, Quaternion.identity);
// or transform.rotation instead of Quaternion.identity.

but the object you want to reference needs to be in the scene.

You'd probably want to use Resources.Load.


// Instantiates a prefab at the path "Assets/Resources/enemy".
function Start () {
    var instance : GameObject = Instantiate(Resources.Load("enemy"));

  • Note: In order for Resources.Load to work, your assets has to be located in a folder (or sub folder) called "Resources".

Some extra thoughts:

If you want to clean up your code a bit and you know you'll be using a static array of objects you want to create, you could make two static/singleton classes to aid you.

  1. A resource loader that preload and store references to resources you later want to reference and expose a strongly typed interface for this. You can probably make use of some editor script to generate this on the fly when the assets change.

  2. A resource factory that use the resource loader to spawn common objects. Then you'd basically just use this in a similar fashion:

This will help your instantiation code become maintainable since all instantiation logic is encapsulated in a single call (with optional parameters if you'd like). This will also allow your objects to be rearranged without having to modify potentially dozens of classes.

At the end, your code could look clean like:

var bomb = Factory.CreateBomb();