Search Unity

Combining gameObject and enum

Discussion in 'Scripting' started by trmhtk2_unity, Jan 14, 2021.

  1. trmhtk2_unity

    trmhtk2_unity

    Joined:
    Mar 29, 2020
    Posts:
    35
    Hello, I created a script that contains enum. The problem is that I want it to be associated with objects, for example: there is a value in enum called TNT and I also have a prefab called that so how can I get the prefab by the enum? Is it too much to do it manually there are hundreds of values there is an automatic way?
     
  2. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    Dictionaries might serve you better. I'm assuming you are spawning said prefabs you are trying to associate with enums.
    Code (CSharp):
    1. //your variables
    2. Dictionary<string, GameObject> gameObjectDic;
    3.  
    4. //populating dictionary
    5. gameObjectDic.Add("TNT", /*your prefab here*/);
    6.  
    7. //example spawn using string tag
    8. GameObject spawnedGO = Instantiate(gameObjectDic["TNT"]);
    You can concievably make a dicitonary like so to use your existing enums as the key instead of a string
    Code (CSharp):
    1. enum myEnum{ TNT, ... }
    2.  
    3. Dictionary<myEnum, GameObject> gameObjectDic;
    Dictionaries have no in-editor representation in the inspector, so you either have to populate this purely in script, or create your own in-editor representation with editor scripting, assuming you need it to appear in inspector.
     
    Last edited: Jan 14, 2021
  3. trmhtk2_unity

    trmhtk2_unity

    Joined:
    Mar 29, 2020
    Posts:
    35
    t
    tanks!