Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
1
Question by PaxForce · Mar 07, 2014 at 09:27 AM · enumpropertiesspell

add properties to enum values

I created a simple Spells script:

 public class Spells_scr : MonoBehaviour {    
     public enum Spells {Shock, Ignite, AcidSpray};    
 }

I would like to add some properties to the "spells". In pseudo-code it woul look like this:

 Spell.Ignite
 {
    _spellPower = 30;
    _spellDuration = 3;
    _otherProperty = otherValue;
    _anotherProperty = anotherValue;
 }

In my Player_2controllerScript I have a function which decreases HP of the player, when he's hit by a spell:

 public void LooseHP()
     {
         _health -= Ignite._spellPower;
         
         
         if(_health <= 0)
         {
             _health = 0;
             
             Debug.Log ("Player_2 has died.");
         }
     }

Is it possible somehow to add properties to those enum values and use them like this?

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
4
Best Answer

Answer by CodeElemental · Mar 07, 2014 at 09:44 AM

It is not possible for Enum's to have properties, as @Jamora suggested. The workaround I would use would be with declaring static instances:

 public class MagicEffect 
 {
     public string Name {get;set;}
     public int SpellPower {get;set;}
     public float Duration {get;set;}
     // Damagetype ...etc ...
 
     public MagicEffect(string name, int spellpower, float duration)
     {
         Name = name;
         SpellPower = spellpower;
         Duration = duration;
     }
     
     public static MagicEffect Ignite = new MagicEffect("Ignite", 30, 0.5);
     public static MagicEffect Shock = new MagicEffect("Shock", 40, 1.5);
     public static MagicEffect AcidSpray = new MagicEffect("AcidSpray", 30, 0.5);
 }

Then your method (has typo btw Lose instead of Loose) would be :

 public void LoseHP()
     {
        _health -= MagicEffect.Ignite.SpellPower;
  
  
        if(_health <= 0)
        {
          _health = 0;
  
          Debug.Log ("Player_2 has died.");
        }
     }

Comment
Add comment · Show 2 · 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 VioKyma · Mar 08, 2014 at 04:25 AM 0
Share

loose hp wouldn't be a very tight implementation

avatar image PaxForce · Mar 08, 2014 at 04:33 PM 0
Share

I'm trying to implement this code into my game just now. I'll let you know how it worked. Thanks.

avatar image
1

Answer by Jamora · Mar 07, 2014 at 09:32 AM

This is not possible in C#, and I assume the same for UnityScript. This is because in C#, enums are just named ints (though they can be any integral type except char).

In other programming languages, Java for example, this would be possible. Enums over there are objects, just like everything else.

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
1

Answer by Phles · Mar 07, 2014 at 11:29 AM

Hey there PaxForce, the answer CodinRonin supplied is perfectly adequate, but as I'd already started thinking about it I thought I'd still post what I came up with, while not striclty answering the question of adding properties to enum values it may be a nice solution in your exact scenario of spell properties, and in an inspector friendly fashion too. I like to leverage the power of Unity's Inspector where ever possible. I may have thought about it too much and come upwith an overly contrived solution but anyway heres is what I would do...

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

 //Serializable class to hold spell data.
 [System.Serializable]
 public class SpellData
 {
     public string spellName;
     public int spellPower;
     public int spellDuration;
     //Other fields here...
 }
 
 public class Spells : MonoBehaviour
 {   
     //Marking list with SerializeField attribute so it saves and shows in Inspector.
     [SerializeField]
     List<SpellData> spells = new List<SpellData>();

     //Dictionary populated in OnEnable to look up spells by name.        
     Dictionary<string, SpellData> spellLookup;
 
     void OnEnable()
     {  
         //Create and populate the lookup dictionary with the list of spells.
         spellLookup = new Dictionary<string,SpellData>();
         for (int i=0; i < spells.Count; i++)
         {
             SpellData spell = spells[i];
             if (!spellLookup.ContainsKey(spell.spellName))
             {
                 spellLookup.Add(spell.spellName, spell);
             }
         }
     }

     //Method to get SpellData by name.
     //Returns null if there is no spell with matching name.    
     public SpellData GetSpell(string spellName)
     {
         SpellData spellData = null;
         if (!spellLookup.TryGetValue(spellName, out spellData))
         {
             Debug.LogError("Spells - No SpellData with name: "+spellName);
         }
         return spellData;
     }

     //Indexer, provides a nicer to write way of accessing SpellData 
     public SpellData this[string spellName]
     {
         get { return GetSpell(spellName); }        
     }
 }

And then the use of this in a player controller...

     //Assign the Spells MonoBehaviour to this in the Inspector.
     //Or get a reference in the Start method of the controller.
     public Spells spells;
 
     public void LoseHP()
     {
         _health -= spells["Ignite"].spellPower;
 
         if (_health <= 0)
         {
             _health = 0;
 
             Debug.Log("Player_2 has died");
         }
     }

Using a serialized object to hold spell data and having a serialized list of these objects means Unity will show them nicely in the inspector for you to add to or edit. it isn't static and it does rely on strings to access the data by the use of the GetSpell() method or the indexer but personally I think it is nicer and more flexible than a load of static instances.

alt text


spellscapture.png (9.5 kB)
Comment
Add comment · Show 2 · 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 PaxForce · Mar 08, 2014 at 04:31 PM 0
Share

hey Phles - what you created here is really awesome, yet I still decided to accept Codin's answer for one simple reason. I'm a Unity and C# noob and looking at your script you almost made me cry, because I realized the extent of my noobishness in Unity and C# program$$anonymous$$g :( I understood only a fraction of what you have written...I had to think hard studying what Codin wrote but eventually I got it. I think. Thank you for the effort anyway, I'll copied your code and saved it for some other time, when I'll be able to read and understand it.

avatar image HuEdOut · Mar 07, 2017 at 02:24 AM 0
Share

I know a reply after 3 years doesn't make much sense, but you just saved me an absurd amount of work and headaches. I just wanted to thank you! I'm using this for ingredients in a food game.

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

24 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

Related Questions

enum in inspector? 2 Answers

How to expose script properties in C# ? 3 Answers

What built-in shader properties are there? 0 Answers

Show few Original Properties beside Custom Editor items . 0 Answers

Photon JoinRandomRoom customGameProperties? Load proper scene 0 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