Search code examples
unity-game-engineunityscript

Trying to access another script in another GameObject


I have two GameObject, a door and the trigger. each GameObject has a script in each one, the trigger has PlayerDoorTrigger.js detects if the player enters the trigger. While the door has doorMove.js opens the door when clicked on.

I'm having a problem getting the boolean from PlayerDoorTrigger.js into an if statement from doorMove.js. Here are the two scripts below:

doorMove.js

var doorDynamic = false;

var playerTrigger:GameObject;


function Awake () {

}
function Start () {
    playerDoorTrigger.playerOnTrigger = true;
}

function Update () {
    if(Input.GetMouseButton(0)){
        doorDynamic=true;
    }
    if(doorDynamic == true){
        transform.Rotate(Vector3.up * Time.deltaTime*128);
    }
    }

function OnCollisionEnter(doorCol:Collision){
    if(doorCol.gameObject.tag=="Walls"){
        Debug.Log("POP");
        doorDynamic = false;
    }   
}

PlayerDoorTrigger

public var playerOnTrigger = false;

function OnTriggerEnter(trigger:Collider){
    if(trigger.gameObject.tag=="Player"){
        playerOnTrigger=true;
    }
}

function OnTriggerExit(trigger:Collider){
    if(trigger.gameObject.tag=="Player"){
        playerOnTrigger=false;
    }
}

Tried following the scripting reference in using GetComponent but no luck.

Please help me solve this, thanks.


Solution

  • You need to get your PlayerDoorTrigger component before you can use it. Here is a quick example that assumes PlayerDoorTrigger and doorMove are attached to the same game object:

    var playerDoorTrigger = GetComponent("PlayerDoorTrigger") as PlayerDoorTrigger;
    
    if (playerDoorTrigger.playerOnTrigger) {
        Debug.Log("Huzzah, player trigger true.");
    }
    

    I'm assuming both of your scripts are in UnityScript (javascript). If not, you need to find other ways of getting Unity to recognize the script classes, so you can assign variables of that type.