Hey Guys,
I need to call a function with two arguments via SendMessage. I recently found out that I have to do it by using a array because SendMessage can only send One Value… So I stored my two values into a array, But the transmission still doesn’t work.
Error Message:
Failed to call function SetVelocityZ of class PlayerMotor
Calling function SetVelocityZ with 1 parameter but the function requires 2.
Here is a snippet of the sending script(JS):
function FixedUpdate ()
{
var arrayStoreage = new Array ();
arrayStoreage.length = 2;
arrayStoreage[0] = controllerNumber;
arrayStoreage[1] = velocityZ;
if(isGrounded == true)
{
GameObject.Find("Player").SendMessage("SetVelocityZ", arrayStoreage);
}
}
And here is the receiving script (JS):
private var velocityZfromLeft : float;
private var velocityZfromRight : float;
function SetVelocityZ(controllerNumber : int, velocityInput : float)
{
if(controllerNumber == 0)
velocityZfromLeft = velocityInput;
print("Left works");
if(controllerNumber == 1)
velocityZfromRight = velocityInput;
print("Right works");
}
The array seams to work, maybe I have to change something in my function… Any Ideas??
SetVelocityZ should declare and use the argument as Array, like this:
function SetVelocityZ(parms: Array){
{
if(parms[0] == 0){
velocityZfromLeft = parms[1];
print("Left works");
}
if(parms[0] == 1){
velocityZfromRight = parms[1];
print("Right works");
}
}
NOTE: You should avoid calling Find functions at Update or FixedUpdate - declare a member variable and assign the object to it at Start:
var player: GameObject; // declare this variable outside any function
function Start(){
player = GameObject.Find("Player");
}
function FixedUpdate(){
...
if(isGrounded == true)
{
player.SendMessage("SetVelocityZ", arrayStoreage);
}
...
Better yet, you could save a reference to the player script at Start, and call SetVelocityZ directly with the two original parameters (replace PlayerScriptName below with the actual player script name):
var playerScript: PlayerScriptName; // use the actual player script name as the variable type
function Start(){
playerScript = GameObject.Find("Player").GetComponent(PlayerScriptName);
}
function FixedUpdate ()
{
if(isGrounded == true)
{
playerScript.SetVelocityZ(controllerNumber, velocityZ);
}
}
The receiving script would be your original version:
private var velocityZfromLeft : float;
private var velocityZfromRight : float;
function SetVelocityZ(controllerNumber : int, velocityInput : float)
{
if(controllerNumber == 0)
velocityZfromLeft = velocityInput;
print("Left works");
if(controllerNumber == 1)
velocityZfromRight = velocityInput;
print("Right works");
}