call function from variable

Interesting unity

I can call a function from a variable;

dog=dothis;

function dothis(){}
dog(); //will call dothis;

Works fine but I cannot include any arguments.

dog=dothis("cat");

function dothis(pet){Debug.Log(pet)} does not work

Is there a way to call a function from a variable with arguments?

Dan

Never saw something like this to be honest :eyes:. Javascript is weird.

Anyway, you can use SendMessage:

// Calls the function ApplyDamage with a value of 5
SendMessage ("ApplyDamage", 5.0);

// Every script attached to the game object 
// that has a ApplyDamage function will be called.
function ApplyDamage (damage : float) {
    print (damage);
}

Probably not. You could probably do something like:

dog=dothis;

function dothis(){}
dog("cat");

But more importantly… why are you trying to do this? What are you using this to accomplish? There is probably another way to accomplish the same task.

Thanks for both suggestions. I think I can make use of both of them. The last one worked also.

I’m trying to let a user write in code from an editor in javascript then convert it to unity. In javascript you can write a function can be assigned to a variable. Not so in Unity.

Also there is some cool javascript that makes it easy for someone to write code.

Like dog=new Object();
dog.sound=“bark”
dog.eat=function eat();
like that.

Is much simpler than how you would do it in Unity.

In unity this would be really complicated for the user to write themselves.

So I guess the answer is I’m trying to come up with easy ways for a user to write code and have it converted to unity.