Accessing variables inside functions?

Hello. If I am defining a variable during a function, how can I make it act like a public/static variable, so that it can be accessed by another script?

Specifically I want to access the "totalBounds" variable that is in this script...

function Start (){
    var totalBounds = GetComponentInChildren(Collider).bounds;
    var colliders = GetComponentsInChildren(Collider);
    for (col in colliders) totalBounds.Encapsulate(col.bounds);
    transform.position+=Vector3(totalBounds.extents.x,0,0);
}

from another script which is instantiating that object. Basically, I want to spawn an object, have it get the totalBounds variable, and have that be used in the the first script.

Thanks

Hi,

Simply declare totalBounds at the top of your script. Add the public keyword for clarity as well.

public var totalBounds;

function Start (){
    totalBounds = GetComponentInChildren(Collider).bounds;
    var colliders = GetComponentsInChildren(Collider);
    for (col in colliders) totalBounds.Encapsulate(col.bounds);
    transform.position+=Vector3(totalBounds.extents.x,0,0);
}

Just declare outside the block:

var totalBounds;
var colliders;

function Start (){
    totalBounds = GetComponentInChildren(Collider).bounds;
    colliders = GetComponentsInChildren(Collider);
    for (col in colliders) totalBounds.Encapsulate(col.bounds);
    transform.position+=Vector3(totalBounds.extents.x,0,0);
}

And you want to access it from another script:

  1. If the 2 scripts attached to same Object:

GetComponent(your_script_name).totalBounds = xxx;

  1. If not attached to same object, then you need to specify which object:

GameObject.Find("your object name).GetComponent(your_script_name).totalBounds = xxx;