Reputation: 329
I'm writing an OnTriggerStay(Collider other)
(in a ladder script) function to let a player climb a ladder and I want to know how to call a function (or access a variable) from the collided object.
I tried using the below solution but Unity tells me it is not valid in this context. Could someone suggest a solution?
myObject.GetComponent<MyScript>().MyFunction(); //wrong
Function
void OnTriggerStay(Collider other) //Runs once per collider that is touching the player every frame
{
if (other.CompareTag ("Player")) { //A player is touching the ladder
//I want to get the isGrounded variable or getIsGrounded() function from other's playerScript.
if (Input.GetAxis ("Vertical") < 0) { // Player should go down
other.transform.Translate (0, -.1f, 0);
}
else if (Input.GetAxis("Vertical") > 0) //Player should go up
other.transform.Translate(0,.1f,0);
}
}
Upvotes: 1
Views: 3296
Reputation: 125275
I want to get the isGrounded variable or getIsGrounded() function from other's playerScript.
The Collider other
parameter from the OnTriggerStay
function contains this information.
That should be: other.GetComponent<MyScript>().getIsGrounded
void OnTriggerStay(Collider other) //Runs once per collider that is touching the player every frame
{
if (other.CompareTag("Player"))
{ //A player is touching the ladder
//I want to get the isGrounded variable or getIsGrounded() function from other's playerScript.
if(other.GetComponent<MyScript>().getIsGrounded)
{
}
if (Input.GetAxis("Vertical") < 0)
{ // Player should go down
other.transform.Translate(0, -.1f, 0);
}
else if (Input.GetAxis("Vertical") > 0) //Player should go up
other.transform.Translate(0, .1f, 0);
}
}
Note that if you want OnTriggerStay
to be called every frame, I suggest you use the combination of OnTriggerEnter
and OnTriggerExit
to accomplish this instead of OnTriggerStay
. See this post of a full example.
Upvotes: 4