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 pieandseal · Jan 01 at 07:45 PM · enumitemabstract

Call function based off enum state?

So im working on a game that has the player use a variety of items, all tied to the same 3 keys (i.e. if itemKey1 has the greatsword state, then pressing itemKey1 will use the greatsword). at the moment i have an input handler class that stores the state and checks for input, it then calls a function in my "UseItem" class, and in that, it checks, in a series of if statements, what item is selected, then calls a different function depending.

 public enum ItemType 
 {
     rapier, greatsword, bow
 }
 public class InputHandler : MonoBehaviour
 {
     [Header("INPUTS")]
     public static KeyCode itemKey1 = KeyCode.J;
     public static KeyCode itemKey2 = KeyCode.K;
     public static KeyCode itemKey3 = KeyCode.L;
 
     public static KeyCode runKey = KeyCode.LeftShift;
 
     [Header("ENUMS")]
     public ItemType item1;
     public ItemType item2;
     public ItemType item3;
 
     [Header("SCRIPT REFERENCES")]
 
     UseItem use;
 
     private void Start()
     {
         use = FindObjectOfType<UseItem>();
     }
 
     private void Update()
     {
         InputItem();
     }
     void InputItem()
     {
         if (Input.GetKeyDown(itemKey1))
         {
             use.InputUse(item1);
         }
 
         if (Input.GetKeyDown(itemKey2))
         {
             use.InputUse(item2);
         }
 
         if (Input.GetKeyDown(itemKey3))
         {
             use.InputUse(item3);
         }
     }
 }

 public class UseItem : MonoBehaviour
 {
     RapierAttack rapier;
     GreatswordAttack greatsword;
     PlayerBow bow;
     private void Start()
     {
         rapier = GetComponent<RapierAttack>();
         greatsword = GetComponent<GreatswordAttack>();
         bow = GetComponent<PlayerBow>();
     }
 
     public void InputUse(ItemType item)
     {
         if(item == ItemType.rapier)
         {
             if(rapier.canUse)
                 rapier.Use();
         }
         else if(item == ItemType.greatsword)
         {
             if (greatsword.canUse)
                 greatsword.Use();
         }else if(item == ItemType.bow)
         {
             bow.Use();
         }
     }
 }


This all works, but my concern is that it isnt very expandable. i would like to call one function that is overidden by the specific Use() function that is applicable. Ive heard about abstract classes, but i dont really understand them. would scriptable objects be of any use? Sorry for the really long question, any help is welcome!

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

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Captain_Pineapple · Jan 01 at 09:35 PM

Hello there,

this use case is the exact reason what Object Oriented Programming is for. You idea that your current approach with cause issues down the road is exactly correct. What you want to do here is the following:

Change your current UseItem class into this format:

 public class UsableItem : MonoBehaviour
     {
         public virtual void UseItem()
         {
             throw new System.NotImplementedException("This function must not be called. It must be overridden.");    
         }
     }
 
     //example for your Bow:
     public class Bow : UsableItem
     {
         public override void UseItem()
         {
             //do whatever you need to do to use your bow
         }
     }
     //example for a Sword:
     public class Sword : UsableItem
     {
         public override void UseItem()
         {
             //do whatever you need to do to use your sword
         }
     }

Both the Bow and Sword class can now be stored in a UsableItemreference. In addition they each call their respective UseItem function when being called upon. Based on this you could just store a direct reference to an usable Item in your InputControl script:

 public class InputControl : MonoBehaviour
     {
         [Header("INPUTS")]
         public static KeyCode[] slotKeys = {
             KeyCode.J,
             KeyCode.K,
             KeyCode.L
         };
 
         public UsableItem[] ItemSlots = new UsableItem[slotKeys.Length];
 
         public void Update()
         {
             for(int i=0;i<slotKeys.Length;i++)
             {
                 if(Input.GetKeyDown(slotKeys[i]))
                 {
                     if (ItemSlots[i] != null)
                         ItemSlots[i].UseItem();
                 }
             }
         }
     }

This way you have an easy way to extend your slots by simply adding another key. You can additionally add more weapon behaviours in a really easy way.

Let me know if that helped or if something was unclear.

Comment
Add comment · Show 3 · 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 pieandseal · Jan 01 at 11:19 PM 0
Share

Thank you for the response!

where am I assigning the right ItemType to each key? How does the script know what item is active when i press KeyCode.J for instance.

I applied your code in my scripts and the UseItem() function is being called properly, but nothing happens from there

avatar image pieandseal pieandseal · Jan 01 at 11:33 PM 0
Share

nvm.... I just forgot to assign the scripts in the editor :P

one more question, the way i previously had it set up was in such a way that i could assign items to a key using the enum state. alt text

i could change what key does what in real time, which is an important feature. Is there any way i could do this with this new system?

screenshot-2022-01-01-152445.png (33.5 kB)
avatar image Captain_Pineapple pieandseal · Jan 02 at 10:27 AM 0
Share

well yes that is kind of not really possible with this version.

You can simply assign a different item in a slot. Even at runtime. You will always call the UseItem function of this specific item instance.

If you have a specific need for this current feature then you can keep your enum, add a state None in the Enum and check if any Item(1/2/3) is != None. If it is then call the use function of this item. (Not really sure if that is such a good idea though...) With this i'd see no good way to make your code easy to maintain as you'd always have to do some more things to add a new item.

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

134 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

Related Questions

enum in generic subclass shows as integer 1 Answer

Need assistance with SubType in custom class (UnityScript or C#) 2 Answers

Item type script using classes isn't working 1 Answer

How can I refactor an enum so that it is still available in the inspector? 1 Answer

idea for a script of a gameobject with different types/roles 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