我正在编写OnTriggerStay(Collider other)
(在梯形图脚本中)函数让玩家爬上梯子,我想知道如何从碰撞对象中调用函数(或访问变量)。
我尝试使用以下解决方案,但Unity告诉我它在此上下文中无效。有人可以提出解决方案吗?
myObject.GetComponent<MyScript>().MyFunction(); //wrong
功能
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);
}
}
答案 0 :(得分:1)
我想从中获取isGrounded变量或getIsGrounded()函数 其他的playerScript。
Collider other
函数中的OnTriggerStay
参数包含此信息。
那应该是: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);
}
}
请注意,如果您希望每帧都调用OnTriggerStay
,我建议您使用OnTriggerEnter
和OnTriggerExit
的组合来完成此操作,而不是OnTriggerStay
。请参阅完整示例的this帖子。