How do I make a gameobject disappear when I click a button facing it?

I want to make a game about guarding a prison. How do I make a gameobject (The cell bars) disappear when I click a keyboard button facing it? There are multiple cells and i dont want all of them disappear when you click one.

Well, you can raycast from the camera, and if it hits, deactivate the cell bars, or you could check if it’s on screen, and if the player presses a button, and it’s on the screen, deactivate it

What I would do is have the character casting rays from the front, and if the rays hit the Cell Bars and you press the key then the doors open. Please ask any further questions :slight_smile:

I am a Ultra-Noob. How do i do that? Code examples?

Then start reading up.

You want to raycast the object then set the object in code to GameObject bars.

When the raycast hits the object.

bars.SetActive(false);

Example:

ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                if (hit.collider.gameObject.tag == "Bar")
                {
                   
                      hit.transform.gameObject.SetActive(false);
                }
                   
                }

There’s several ways of handling this, and all have different levels of complexity/flexibility.

My favorite way of handling this is with the IPointerHandler interfaces and OnTrigger calls.

with OnPointerEnter+OnPointerExit you can enable the input only if you are looking at the interactible object
with OnTriggerEnter+OnTriggerExit you can enable the input only if the user is close enough to the interactible Object

by using both then the user has to both be close enough and looking at the interactible to interact with it.

One issue with Raycasting is you need to be looking directly at the object to interact with it. For large objects like doors thats not an issue. but for tiny objects, or where a screenspace is cluttered with a high number of objects it could be a chore for the player to highlight the correct object. You can use larger colliders so that you don’t have to look directly at them (and this is typically how its commonly done when using the raycast option) but it doesn’t solve the clutter issue.

So for things like Item pickups, I use OnTriggers to build a list of possible pickups. Then on Update only be interactible to the pickup with the highest dot product to my camera’s direction (imagine trying to pick up a specific item in a clutter of items, the dot product helps you pick up the item you’re most looking at). or instead of Dot you could use (camera.WorldToViewport(itemPosition) - new Vector2(0.5f,0.5f)).sqrMagnitude and favor the one with the lowest value, the result should be the same.

I got the rays done, now how do i make it appear and disappear by clicking it?