簡體   English   中英

如何從碰撞對象統一獲取變量或調用函數

[英]How to get variable or call function from collider object in unity

我正在編寫一個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);
    }

}

我想從其他人的playerScript中獲取isGrounded變量或getIsGrounded()函數。

OnTriggerStay函數中的Collider other參數包含此信息。

那應該是: 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 ,建議您使用OnTriggerEnterOnTriggerExit的組合來代替OnTriggerExit來完成此OnTriggerStay 請參閱示例的完整示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM