Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 Skourge · Mar 08 at 03:31 AM · updateinventoryammoarrowbow

Have my number of arrows correspond to arrows in my inventory

Hello.

Fairly new to coding so I'm really struggling how to code this. I have followed a youtube tutorial to get a whole inventory system working in my game. I've also added a bow and arrow that can fire arrows, it has a number of arrows that goes down after each shot but i'd like that number to correspond to one of my arrow items in my inventory, so I pick up (or craft) 10 arrows, it goes into my inventory and my bow script updates the amount of arrows left.

Here are my scripts.

---SCRIPT FOR EACH ITEM---

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Item : MonoBehaviour { public string equipmentType; public int equipmentIndex;

 public Sprite itemSprite;

 public int amountInStack = 1;

 public int maxStackSize = 1000;

 public int itemID;

}

---SCRIPT FOR EACH SLOT---

using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine;

public class Slot : MonoBehaviour { public Item slotsItem;

 Sprite defaultSprite;
 Text amountText;
 
 

 public void CustomStart()
 {
     defaultSprite = GetComponent<Image>().sprite;
     amountText = transform.GetChild(0).GetComponent<Text>();
     amountText.text = "";
     
 }

 public void DropItem()
 {
     if(slotsItem)
     {
         slotsItem.transform.parent = null;
         slotsItem.gameObject.SetActive(true);
         slotsItem.transform.position = Vector3.zero;
     }
 }


 public void CheckForItem()
 {
     if(transform.childCount > 1)
     {
         slotsItem = transform.GetChild(1).GetComponent<Item>();
         GetComponent<Image>().sprite = slotsItem.itemSprite;
         if (slotsItem.amountInStack > 1)
             amountText.text = slotsItem.amountInStack.ToString();
         
     }
     else
     {
         slotsItem = null;
         GetComponent<Image>().sprite = defaultSprite;
         amountText.text = "";
         

     }
 }

}

---SCRIPT FOR INVENTORY---

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Inventory : MonoBehaviour { public GameObject inventoryObject;

 public Slot[] slots;

 public GameObject player;
 public GameObject NewPickAxe;
 public GameObject NewHatchet;
 public GameObject WoodenBow;
 public GameObject ArrowShoot;

 public Slot[] equipSlots;

 private void Start()
 {
     foreach (Slot i in slots)
     {
         i.CustomStart();
     }
     foreach (Slot i in equipSlots)
         i.CustomStart();
 }
 private void Update()
 {
     {
         if (Input.GetKeyDown(KeyCode.Tab))
         {
             inventoryObject.SetActive(!inventoryObject.activeInHierarchy);

             if (inventoryObject.activeInHierarchy)
             {
                 ShowMouseCursor();
                 player.GetComponent<SC_FPSController>().canMove = false;
                 NewPickAxe.GetComponent<NewPickAxeSwing>().enabled = false;
                 NewHatchet.GetComponent<NewHatchetSwing>().enabled = false;
                 WoodenBow.GetComponent<BowShoot>().enabled = false;
                 ArrowShoot.GetComponent<Shooting>().enabled = false;

             }
             else 
             {
                 HideMouseCursor();
                 player.GetComponent<SC_FPSController>().canMove = true;
                 NewPickAxe.GetComponent<NewPickAxeSwing>().enabled = true;
                 NewHatchet.GetComponent<NewHatchetSwing>().enabled = true;
                 WoodenBow.GetComponent<BowShoot>().enabled = true;
                 ArrowShoot.GetComponent<Shooting>().enabled = true;
             }

         }
     }

     foreach (Slot i in slots)
     {
         i.CheckForItem();
     }
     foreach (Slot i in equipSlots)
         i.CheckForItem();
 }


 public int GetItemAmount(int id)
 {
     int num = 0;
     foreach(Slot i in slots)
     {
         if (i.slotsItem)
         {
             Item z = i.slotsItem;
             if (z.itemID == id)
                 num += z.amountInStack;
         }
     }
     return num;
 }

 public void RemoveItemAmount(int id, int amountToRemove)
 {
     foreach(Slot i in slots)
     {
         if (amountToRemove <= 0)
             return;

         if(i.slotsItem)
         {
             Item z = i.slotsItem;
             if(z.itemID == id)
             {
                 int amountThatCanBeRemoved = z.amountInStack;
                 if(amountThatCanBeRemoved <= amountToRemove)
                 {
                     Destroy(z.gameObject);
                     amountToRemove -= amountThatCanBeRemoved;
                 }
                 else
                 {
                     z.amountInStack -= amountToRemove;
                     amountToRemove = 0;
                 }
             }
         }
     }
 }




 // HIDE AND SHOW MOUSE CURSOR
 public void ShowMouseCursor()
 {
     Cursor.visible = true;
     Cursor.lockState = CursorLockMode.None;
 }

 public void HideMouseCursor()
 {
     Cursor.visible = false;
     Cursor.lockState = CursorLockMode.Locked;
 }






 public void AddItem(Item itemToBeAdded, Item startingItem = null)
 {
     int amountInStack = itemToBeAdded.amountInStack;
     List<Item> stackableItems = new List<Item>();
     List<Slot> emptySlots = new List<Slot>();

     if (startingItem && startingItem.itemID == itemToBeAdded.itemID && startingItem.amountInStack < startingItem.maxStackSize)
         stackableItems.Add(startingItem);

     foreach (Slot i in slots)
     {
         if (i.slotsItem)
         {
             Item z = i.slotsItem;
             if (z.itemID == itemToBeAdded.itemID && z.amountInStack < z.maxStackSize && z != startingItem)
                 stackableItems.Add(z);
         }
         else
         {
             emptySlots.Add(i);
         }
     }

     foreach (Item i in stackableItems)
     {
         int amountThatCanBeAdded = i.maxStackSize - i.amountInStack;
         if (amountInStack <= amountThatCanBeAdded)
         {
             i.amountInStack += amountInStack;
             Destroy(itemToBeAdded.gameObject);
             return;
         }
         else
         {
             i.amountInStack = i.maxStackSize;
             amountInStack -= amountThatCanBeAdded;
         }
     }

     itemToBeAdded.amountInStack = amountInStack;
     if (emptySlots.Count > 0)
     {
         itemToBeAdded.transform.parent = emptySlots[0].transform;
         itemToBeAdded.gameObject.SetActive(false);
     }
 }
 private void OnTriggerEnter(Collider col)
 {
     if (col.GetComponent<Item>())
         AddItem(col.GetComponent<Item>());
 }

}

---SCRIPT FOR BOW---

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Shooting : MonoBehaviour { [SerializeField] float pullSpeed; [SerializeField] GameObject arrowPrefab; [SerializeField] GameObject arrow; [SerializeField] int numberOfArrows = 10; [SerializeField] GameObject bow; bool arrowSlotted = false; float pullAmount = 0;

 public Animator anim;
 public Animator anim2;

 public GameObject arrowsetactive;


 public Transform fireArrow;

 private AudioSource source;
 public AudioClip fire;
 public AudioClip draw;

 

 




 // Start is called before the first frame update
 void Start()
 {
     anim = anim.GetComponent<Animator>();
     source = GetComponent<AudioSource>();
 }

 // Update is called once per frame
 void Update()
 {
     ShootLogic();
 }

 void SpawnArrow()
 {
     if(numberOfArrows > 0)
     {
         arrowSlotted = true;
         
         arrow = Instantiate(arrowPrefab, fireArrow.position, fireArrow.rotation) as GameObject;



         
         arrow.transform.parent = transform;
     }
 }

 void ShootLogic()
 {
     if (numberOfArrows > 0)
     {
         if (pullAmount > 100)
             pullAmount = 100;

         Rigidbody _arrowRigidB = arrow.transform.GetComponent<Rigidbody>();
         ProjectileAddForce _arrowProjectile = arrow.transform.GetComponent<ProjectileAddForce>();

         
         
         if (Input.GetMouseButton(0))
         {
             
             pullAmount += Time.deltaTime * pullSpeed;
             Debug.Log(pullAmount.ToString());
             

             if (Input.GetMouseButtonDown(0))
             {
                 Invoke("PlayDrawSound", 0.8f);
             }


         }
         if (Input.GetMouseButtonUp(0))
         {
             
             arrowSlotted = false;
             
             _arrowRigidB.isKinematic = false;
             arrow.transform.parent = null;

             
             anim2.GetComponent<Animator>().enabled = false;
             

             anim.enabled = false;
             _arrowRigidB.AddForce(transform.forward * ((pullAmount * 25) + .05f));
             numberOfArrows -= 1;

             PlayHitSound();


             pullAmount = 0;

             _arrowProjectile.enabled = true;


         }
         
         if (Input.GetMouseButtonDown(0) && arrowSlotted == false)
             


         Invoke("SpawnArrow", 2.0f);






     }  
 }


 private void PlayHitSound()
 {
     source.clip = fire;
     source.Play();
 }

 private void PlayDrawSound()
 {
     source.clip = draw;
     source.Play();
 }


}

Thanks soo much if you've read all of this, I know its a lot. But just an idea in the right direction would help soo much. (sorry if it's a little messy, not sure how to copy/paste the scripts properly)

Comment
Add comment
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

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Monsoonexe · Mar 08 at 03:54 AM

To map data, consider a Dictionary. They work like arrays except you can use anything as the key instead of an integer. So maybe Dictionary, where string is the name or type of your item and int is the amount in 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
avatar image
0

Answer by Skourge · Mar 08 at 03:56 AM

Hey thanks for that, how does that look in the form of code? Just a tiny example?

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
avatar image
0

Answer by BurgessBH · Mar 08 at 05:45 AM

Thanks for the information, I will try to figure it out for more. Keep sharing such informative post keep suggesting such post.

MyKohlscharge.com

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

140 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

Related Questions

How can I nail an arrow to an enemy(In 2D)? 1 Answer

How to get an animation script working? 1 Answer

Will the new GUI break the old GUI system? 2 Answers

I need help writing an animation script for a Bow and Arrow weapon 1 Answer

need help deleting ammo item in inventory on gun reload 1 Answer


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