Opening/Closing doors
I was wondering if somebody could explain door opening/closing code to me please. as far as i know i need two different scripts, one on the player and another on the door (i will be having several doors in the scene). I would like to be casting a ray from my player looking for the doors, once it finds one it accesses the script thats on the door. Here's what i have so far. thanks.
Script on the player
public float rayDistance = 3f;
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ViewportPointToRay (new Vector3 (0.5f, 0.5f, 0f));
}
}
script on the door
//access player raycast
if (Input.GetKeyDown (KeyCode.E))
{
print ("e was pressed");
if (Physics.Raycast (ray, out hit, rayDistance))
{
print ("Ray hit a surface");
if (hit.collider.gameObject.thisobject)
{
print ("ray cast on door");
Answer by mat750 · Nov 16, 2015 at 04:32 PM
One thing to keep in mind is that variables are not automatically shared between scripts. You have to move the code from the door script to the player script.
$$anonymous$$ove the code? This doesnt sound like a solution. Or is that not what you meant.
Use GetComponent to access variables of another script. Use it to cache the script reference in Start() and you can access the other script without processing penalty.
GetComponent would work, and is probably what op wants to do. However since op's ray starts at the camera it makes more sense to do the raycast from there.