Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Mistyisty123 · Aug 01, 2019 at 07:25 PM · raycastinventoryraycasthitaddhit detection

Raycast is finding all items/script is finding all items - inventory help

Hello,

I have an inventory, and trying to do picking up items using Raycast! It all works fine, however it finds all the "items", and adds them to the inventory not the hitInfo item, what would be the solution for this, so that it only adds the item I'm looking at and not all of them?

The code is below:

 using UnityEngine;
 using System.Collections;
 public class PickUpItem : MonoBehaviour
 {
     public Item item;
     private Inventory _inventory;
     private GameObject _player;
     // Use this for initialization
 
     private Camera mainCamera;
     private Interact interact;
 
     void Start()
     {
         mainCamera = Camera.main;
         interact = GameObject.FindGameObjectWithTag("Player").GetComponent<Interact>();
         _player = GameObject.FindGameObjectWithTag("Player");
         if (_player != null)
             _inventory = _player.GetComponent<PlayerInventory>().inventory.GetComponent<Inventory>();
     }
 
     // Update is called once per frame
     void Update()
     {
         Ray ray = mainCamera.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
         RaycastHit hitInfo;
 
         if(Physics.Raycast(ray, out hitInfo, interact.interactRange))
         {
             if (_inventory != null && Input.GetKeyDown(KeyCode.E) && hitInfo.collider.tag == "FoodItem")
             {
                 bool check = _inventory.checkIfItemAllreadyExist(item.itemID, item.itemValue);
                 if (check)
                     Destroy(hitInfo.collider.gameObject);
                 else if (_inventory.ItemsInInventory.Count < (_inventory.width * _inventory.height))
                 {
                     _inventory.addItemToInventory(item.itemID, item.itemValue);
                     _inventory.updateItemList();
                     _inventory.stackableSettings();
                     Destroy(hitInfo.collider.gameObject);
                 }
             }
         }
     }
 }
Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image niiicolai · Aug 01, 2019 at 08:40 PM 0
Share

You have to provide your code for your inventory in order to answer this question. :-)

avatar image niiicolai · Aug 01, 2019 at 08:41 PM 0
Share

Also in your Raycast's "if statement" it doesn't seem like you ever set the item to anything new, which probably also is causing you problems.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by niiicolai · Aug 01, 2019 at 09:02 PM

Hi @Mistyisty123 You could do something like this:


 using UnityEngine;
 using System.Collections;
 public class PickUpItem : MonoBehaviour {
   public string title;
   public int amount;
 }


 using UnityEngine;
 using System.Collections;
 public class InventoryController : MonoBehaviour {

   [SerializeField] private itemTag = "Item"; // Remember to setup your tag, aswell on the gameobjects.

   private List<string> items;
   private List<int> amounts;

   [SerializeField] private KeyCode interactKey;
   [SerializeField] private float interactRange;
   private RaycastHit hitInfo;

   private void Start() {
     items = new List<string>();
     amounts = new List<int>();
   }

   private void Update() {

     if (Input.GetKeyDown(interactKey) {
       Ray ray = Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
  
        if (Physics.Raycast(ray, out hitInfo, interactRange)) {
          if (hitInfo.CompareTag(itemTag)) {
             var item = hitInfo.collider.GetComponent<PickUpItem>();
             AddItem(item.title, item.amount);
             Destroy(item.gameObject);
          }
        }
      }
   }
 
   public void AddItem(string itemTitle, int amount) {
     var exist = false;
     for (int i = 0; i < items.Count; i++) {
       if (items[i] == itemTitle) {
         amounts[i] += amount;
         exist = true;
         break; // Remember to break the loop
     }
 
     if (!exist) {
       items.Add(itemTitle);
       amounts.Add(amount);
     }
   }
 
   public void RemoveItem(string itemTitle, int amount) {
     for (int i = 0; i < items.Count; i++) {
       if (items[i] == itemTitle) {
         amounts[i] -= amount;
         if (amounts[i] <= 0) {
           items.RemoveAt(i);
           amounts.RemoveAt(i);
         }
         break; // Remember to break the loop
       }
     }
   }

   // The inventory script above saves the item title and amount. 
   // If you later want to get that item out as a GameObject you would need to do add
   // something like this to the inventory controller.

   [SerializeField] private PickUpItem[] itemPrefabs;

   private PickUpItem GetItemBy(string title) {
     PickUpItem item = null;
     for (int i = 0; i < itemPrefabs.Length; i++) {
       if (itemPrefabs[i].title == title) {
         item = itemPrefabs[i];
         break;
       }
     }
     return item;
   }

   // When you have a method to get the prefab you can extend your inventory with a drop method
   [SerializeField] private Transform dropPoint;

   private void DropItem(string title, int amount) {
     var canDrop = false;
     for (int i = 0; i < items.Count; i++) {
       if (items[i] == title) {
         canDrop = (amount <= amounts[i]);
         break;
       }
     }

     if (canDrop) {
       var prefab = GetItemBy(title);
       var clone = Instantiate(prefab);
       clone.transform.position = dropPoint.position;
       clone.amount = amount;

       RemoveItem(title, amount);  // Remember to remove the items from your inventory
     }
   }
 }

 









Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

158 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Adding an empty raycast hit to a list 1 Answer

NullReference when checking tag via Raycast. How to solve this? 1 Answer

My raycast randomly stops working. 0 Answers

RayCast not working properly and ray is not hitting an object 1 Answer

Detect RaycastHit on Character Controller 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges