The question is answered, right answer was accepted
Raycast using button
Hi.
I'm trying to make an Android FPS Game.
I'm know how to use Raycasting. But When I'm trying to cast using a Button(Made on the Canvas), it doesn't seems to work.
I'm making a script that opens when I press a button.
I'm sure that nothing is wrong, but dunno why it doesn't work.
Here is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OpenDoor : MonoBehaviour {
public Camera cam;
public Animator door;
bool isOpened;
// Use this for initialization
void Start ()
{
isOpened = false;
}
// Update is called once per frame
public void OnClick ()
{
if (isOpened = false) {
Ray ray = new Ray (cam.transform.position, cam.transform.forward);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 5.0f))
{
if (hit.collider.CompareTag ("WarehouseDoor"))
{
door.SetBool ("Open", true);
isOpened = true;
}
}
}
}
}
Have you tried to put simple Debug.Log and Debug.DrawRay inside your various conditions to check where is the exact problem?
Yep. It doesn't raycast. Should I use void Update and onbuttondown ins$$anonymous$$d of public void OnClick? I'm adding a photo.
Are you sure the click is detected? Does the following code outputs something when you click on the button?
public void OnClick ()
{
Debug.Log( isOpened ) ;
if (isOpened == false)
{
// ....
}
}
I've just tested your script, works fine here. ($$anonymous$$ake sure your door is close enough to your camera, otherwise, the Ray
won't hit)
The problem may come from here:
if (isOpened = false)
Should be :
if (isOpened == false)
Or
if (!isOpened)
Nope. Doesn't work. I already checked for all of my Animators and Cameras. Any Idea?
This is the correct source of the problem. Single equation character means the if will always fail.
if(isOpened = false) // always fails if(isOpened == false) // Fails only when isOpened is true