- Home /
How take item if I am bringing rear sight and press key E?
I want take item if I am bringing rear sight and press key E.
I add trigger for Item
//item.cs
public void OnTriggerStay(Collider other){
if (other.tag == "Player"){
Inventory.GetInventory().TakeItem();
}
}
//inventory.cs
public void TakeItem(){
RaycastHit hit;
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (Input.GetKeyDown (KeyCode.E)) {
if (Physics.Raycast(ray, out hit)){
Item item = hit.transform.GetComponent<Item>();
if (item != null){
item.audioTakeItem.Play();
items.Add(item);
item.gameObject.SetActive(false);
}
}
}
}
But this code wrong. I can take item if rear sight in not directed item.
Sorry my wrong English =)
What's the problem? Are you failing to pick up the item? Are you picking up an item that you shouldn't be able to? When does it break, and how is it breaking?
I can take this item, but I dont take, becouse rear sight not directed this item.
Answer by incorrect · Jul 27, 2014 at 09:36 AM
So I've made it like this and it works just as expected.
using UnityEngine;
using System.Collections;
public class RayCaster : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.E)) {
Debug.Log ("Pressed E");
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if(hit.distance < 1f) hit.collider.gameObject.SendMessage("Destroy");
}
}
}
}
Figure out by yourself how to make the rest of logic.
Thank you. If I check clickable item or not, I use this code:
Item item = hit.transform.GetComponent<Item>();
if (item != null){....}
Or this is bad practice?
Yeah, as I know you're doing it right. You can check if the hited object has component or can make it a much more universal way.
void Update () {
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.E)) {
Debug.Log ("Pressed E");
Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if(hit.distance < 1f) hit.collider.gameObject.Send$$anonymous$$essage("Interact", Send$$anonymous$$essageOptions.DontRequireReceiver);
}
}
}
So if it is pickable object, it's Interract() method will add something to inventory and destroy it's instance in the world, if it is door it will open, but the interaction method will be same for everything.
Your answer
![](https://koobas.hobune.stream/wayback/20220613155054im_/https://answers.unity.com/themes/thub/images/avi.jpg)