Backround Loader

Hi, I wrote a java script where if the player gets a certain from an object, that object changes into something else (a lowpoly version or even an empty object). This worked just fine, so I wrote the second part: changing it back when the player gets within a range. Not so fine. I've racked my brain for a possible problem, so I decided to plea for more experienced help. I get no errors at all; it just plain doesn't work.

To try it out your self, make 2 prefabs, one with the backroundloader.js attached and the other with the backroundreloader.js attached. Next assign the target of both to be your player (I use the FPS controller), and tag your player "Player". Lastly assign the object and oldobject to vars to their counterparts, and set a sightdistance. It SHOULD work.... but it just changes to the new object and never changes back, no matter how close I get. ANY help would be appreciated, and if get it working, you can use the scripts in any of your projects Just be sure to let me know how you did it.

Here are the scripts:

backroundloader.js (works fine)

var object : Transform;
var sightRange = 30.0;
var target : Transform;
var changeDelay = 0.0;

function Start () {
    if (target == null && GameObject.FindWithTag("Player"))
        target = GameObject.FindWithTag("Player").transform;
}
    // If the distance is greater than sightRange
    if (Vector3.Distance(transform.position, target.position) > sightRange) {
        Invoke("loadNew", changeDelay);
    }

function loadNew () {
    BroadcastMessage ("outofSight");
}

function outofSight () {
    // Destroy object
    Destroy(gameObject);

    // change to new object
    if (object)
        Instantiate (object, transform.position, transform.rotation);

}

and

backroundreloader.js

var oldobject : Transform;
var sightRange = 5.0;
var target : Transform;
var changeDelay = 0.0;

function Start () {
    if (target == null && GameObject.FindWithTag("Player"))
        target = GameObject.FindWithTag("Player").transform;
}
    // If the distance is less than sightRange
    if (Vector3.Distance(transform.position, target.position) < sightRange) {
        Invoke("loadOld", changeDelay);
    }

function loadOld () {
    BroadcastMessage ("inSight");
}

function inSight () {
    // Destroy object
    Destroy(gameObject);

    // change to old object
    if (oldobject)
        Instantiate (oldobject, transform.position, transform.rotation);

}

You're only checking the distance once. What you should do is check periodically (preferrably not every frame)

e.g.:

function Start () {
    if (target == null && GameObject.FindWithTag("Player"))
        target = GameObject.FindWithTag("Player").transform;

    //check the distance every 0.5s
    InvokeRepeating("CheckDistance", 0.5, 0.5);
}

function CheckDistance()
{
    // If the distance is less than sightRange
    if (Vector3.Distance(transform.position, target.position) < sightRange) {
        Invoke("loadOld", changeDelay);
    }
}