- Home /
Open door with key
This script is for my door. Right now it opens every time I walk into the invisible cube that triggers the door to open. I made a script to pick up a key. Now the big question is how do I change the script below so it triggers only when I have the key. I think I have to somehow call the other script and let this one know I have the key.
Door open script:
var door: Transform; var angleOpen: int; var angleClose: int; var speedOpen: int =1000;
function OnTriggerStay (other: Collider) { if(door.transform.localEulerAngles.y < angleOpen) { door.transform.Rotate(Vector3.up*Time.deltaTime*speedOpen); } }
Below is the pick up script for the key.
private var gotKey : boolean = false;
function OnControllerColliderHit (hit: ControllerColliderHit) {
if(hit.gameObject.name == "key") { print("You Picked Up The House Key"); gotKey = true; Destroy(hit.gameObject);
}
}
Answer by loramaru · Apr 22, 2011 at 04:11 AM
You will indeed need to call a function (or access an public variable) on the other object. For the sake of the example, I'll assume the script with the key code is PlayerScript; but just substitute the real name below. The first thing to do is to add a function to get the key state in that script
private var gotKey : boolean = false;
function HasKey() { return gotKey; }
function OnControllerColliderHit (hit: ControllerColliderHit) { // ... }
Then in your door script, you just need to grab the script on the player object using GetComponent(type). Once you have the component, you can call any public function (or access any public variables, from that script.
function OnTriggerStay (other: Collider) {
var player : PlayerScript = other.gameObject.GetComponent(PlayerScript) as PlayerScript;
if(player != null && player.HasKey()) {
if(door.transform.localEulerAngles.y < angleOpen) {
door.transform.Rotate(Vector3.up*Time.deltaTime*speedOpen);
}
}
}
Thanks. With $$anonymous$$or change I made this work.
PlayerScript = GameObject.Find("Player").GetComponent("PickuUp");
if(PlayerScript.got$$anonymous$$ey) {
Answer by burgunfaust · Apr 22, 2011 at 04:17 AM
I believe this will work.
Key script
var doorKeyOpens : Transform; private var gotKey : boolean = false;
function OnControllerColliderHit (hit: ControllerColliderHit) {
if(hit.gameObject.name == "key") { print("You Picked Up The House Key"); doorKeyOpens.gotKey = true; Destroy(hit.gameObject);
}
}
Door script
var door: Transform; var gotKey : boolean = false; var angleOpen: int; var angleClose: int; var speedOpen: int =1000;
function OnTriggerStay (other: Collider) { if(door.transform.localEulerAngles.y < angleOpen) { door.transform.Rotate(Vector3.up*Time.deltaTime*speedOpen); } }
Your answer
Follow this Question
Related Questions
Help with making his work with a key 1 Answer
Opening an animated door with a keycard 0 Answers
Press an in-game switch to open a door - help? 2 Answers
Open door with key 1 Answer
GUI text, door and object collider 2 Answers