Update Function

Hy people,

I wanna know if exist a way to create the update function on fly, like in flash.

Something like object.Update = function();
Can it be applyed here?

Tnx

You can’t define methods on the fly in Unity JavaScript. This is one of the tradeofs that were made in order to make Unity JavaScript as fast as C#.

You could however use a simple MonoBehaviour that uses a delegate class like the following few lines.

// DynamicUpdate.js -- attach this one to your game object
public var updateDelegate : DelegateBase = null;
function Update() {
    if(updateDelegate) 
        updateDelegate.Invoke();
}
// Delegates.js

class DelegateBase {
    public function Invoke() {
        Debug.Log("Don't use this class directly");
    }
}

class Delegate1 extends DelegateBase {
    public function Invoke() {
        Debug.Log("Inside Delegate1");
    }
}
class Delegate2 extends DelegateBase {
    public function Invoke() {
        Debug.Log("Inside Delegate2");
    }
}

Then… where you originally wanted to define the update method you do:

...
  // Assuming a behaviour attaced to the same go:
  var dyn_update = GetComponent(DynamicUpdate);
  if(dyn_update) {
     dyn_update.updateDelegate = new Delegate1();
     // or
     // dyn_update.updateDelegate = new Delegate2();
  }
  else {
      Debug.Log("Could not find the DynamicUpdate component");
  }
...

A bit more cumbersome, I know… There are also other ways to solve this. You could for instance have the different Update functions in seperate scripts and attach them using AddComponent() depending on which one you want to use or have them all attached and clear or set the enabled property on them.

Hey Keli, thanks a lot…

That sound fine… i mean, it’s will work. I need another advice… please. So, i’ve attached a component script to my game Object… it’s does an series of action, and finaly completes the action. There’s an way to delete, or remove this componnet, or the best way of do that is to set this enabled off?

cy-a

Do you want to do this from the script? Assuming you will not be using that specific instance of the script again I believe this should work.

Destroy(this);

If you want to do it from another script then you GameObject’s GetComponent method to get a handle on the component and use Destroy on the component.

// From another script
theComponent = theGameObject.GetComponent(yourScript);
Destroy(theGameObject);

You might be able to shorten the above to

Destroy(theGameObject.GetComponent(yourScript));

but I am not sure.