- Home /
Reset raycast when an object exits
Hello, I have a small problem with my raycast, I want to make a pressure plate, it would basically press when an object is on it, and go back when the object leaves it. But my pressure plate doesn't go back when the object leaves it. I am not using animations for it as it doesn't work with what I did so I'm changing the y axis of the pressure plate to make it go down and back up.
I think it has to do with the else statement that says "else if (p == null) {", because when I try to Debug.Log something inside it, nothing appears... I tried to make the console say what object has been hit by the raycast, but when it exits, it doesn't say null at the end, it just doesn't say anything. The problem is that the recast doesn't reset, so when the objet exits, the raycast kept the object that was found and keeps it until another one is found...
Here is my script if you want it:
It's in C#
using UnityEngine;
using System.Collections;
public class PressurePlate : MonoBehaviour {
bool isPressed;
public float pushAmt;
public bool nonPlayerAllowed;
public LayerMask layer;
void Update () {
TestForPress ();
}
void TestForPress () {
Vector3 fwd = transform.TransformDirection(Vector3.up);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, out hit, 0.5f, layer)){
Collider p = hit.collider;
if (p != null) {
Debug.Log(p);
if (nonPlayerAllowed == true) {
if (isPressed == true) {
Idle ();
}else if (isPressed == false) {
Press();
isPressed = true;
}
}
else if (nonPlayerAllowed == false && p.tag == "Player") {
if (isPressed == true) {
Idle ();
}else if (isPressed == false) {
Press();
isPressed = true;
}
}
}
else if (p == null){
if (isPressed == true) {
Back ();
isPressed = false;
}else if (isPressed == false) {
Idle ();
}
}
}
}
void Press () {
transform.position = new Vector3(transform.position.x,transform.position.y - pushAmt,transform.position.z);
}
void Back () {
transform.position = new Vector3(transform.position.x,transform.position.y + pushAmt,transform.position.z);
}
void Idle () {
transform.position = transform.position;
}
}
Thank you!
Answer by Tehnique · Apr 11, 2015 at 09:06 AM
You are correct in guessing p is never null, and that is because you are inside this if:
if (Physics.Raycast(transform.position, fwd, out hit, 0.5f, layer)){...}
When the condition for this if is true, p is always != null, just look here. Just change your code to look like:
if (Physics.Raycast(transform.position, fwd, out hit, 0.5f, layer)
{...}
else {
if (isPressed == true) {
Back ();
isPressed = false;
}else if (isPressed == false) {
Idle ();
}
}
Your answer
