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 /
  • Help Room /
avatar image
0
Question by ShaggySlade · Dec 24, 2016 at 11:43 AM · uispriteinheritancelooting

how to make UI work like OnGui.

I been trying to figure out how to do something with Unity's UI that I could do in OnGUI.....I have a base item class with a variable for the icon. when using OnGUI its type was texture2d and I used a for loop with "if(GUI.button)" to display the images representing the items. I was wondering how I achieve the same results using UI.

In the base Item script: (OnGui version) --> private Texture2D _icon; (UI version)--> private Sprite _icon;

In the Chest script: (OnGui version) --> for(int i = 0; i < loot.Count; i++) { if(GUI.Button(new Rect(......), new GUIContent(loot[i]._icon) (UI version)--> ??????not really sure??????

EDIT : here is some snippets from my scripts so you see what I have going on kinda.

My item script has this (and a getter and setter) : private Sprite _icon;

This is my ItemGenerator script:

 using UnityEngine;
 using UnityEngine.UI;
 
 
 public static class ItemGenerator {
 
     public const int BASE_MELEE_RANGE = 1;
     public const int BASE_RANGED_RANGE = 5;
 
     private const string MELEE_WEAPON_PATH = "Items/Weapons/Melee/";
 
 
     public static Item CreateItem()
     {
 
 //decide what type of item to make
 
         //call the method to create that base item type
         Item item = CreateWeapon();
 
 
         //      _name;
         item.Value = Random.Range(1, 101);
         item.Weight = Random.Range(1, 21);
         item.Rarity = RarityTypes.Common;
 
 
 
 //return the new item
         return item;
     }
 
 
     public static Weapon CreateWeapon()
     {
         //decide if the weapon is melee or ranged
         Weapon weapon = CreateMeleeWeapon();
 
 
         //return the weapon created
         return weapon;
 
     }
 
     private static Weapon CreateMeleeWeapon()
     {
         Weapon meleeWeapon = new Weapon();
 
         string[] weaponNames = new string[4];
         weaponNames[0] = "Axe";
         weaponNames[1] = "Axe1";
         weaponNames[2] = "Dagger";
         weaponNames[3] = "Sword";
 
 
         //fill in all the values for that item type
         meleeWeapon.Name = weaponNames[Random.Range(0, weaponNames.Length)];
 
         //assign the max damage
         meleeWeapon.MaxDamage = Random.Range(5, 16);
         meleeWeapon.DamageVariance = Random.Range(.2f, .76f);
         meleeWeapon.TypeOfDamage = DamageType.Slash;
 
         meleeWeapon.MaxRange = BASE_MELEE_RANGE;
 
         //assign the icon for the weapon
         meleeWeapon.Icon = Resources.Load<Sprite>(MELEE_WEAPON_PATH + meleeWeapon.Name) ;
 
     
         //return melee weapon
         return meleeWeapon;
     }
 
 }
 
 
 public enum ItemType
 {
     Armor,
     Weapon,
     Potion,
     Scroll
 }


This is my Chest script:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 
 
 [RequireComponent (typeof(BoxCollider))]
 [RequireComponent(typeof(AudioSource))]
 public class Chest : MonoBehaviour {
 
 
     public enum State
     {
         open,
         close,
         inbetween
     }
 
     public AudioClip openSound;
     public AudioClip closeSound;
 
     public State state;
 
     public float maxDistance = 2.4f;           //Max distance the player can be to open this chest
 
     private GameObject _player;
     private Transform _myTransform;
     public bool inUse = false;
 
     private GameObject lootWindow;
     private GameObject LWitemHolder;
     public GameObject item;
 
     public bool _used = false;                 //track if the chest has been used or not
 
     public List<Item> loot = new List<Item>();
 
     // Use this for initialization
     void Start () {
         lootWindow = GameObject.Find("Loot Window");
         LWitemHolder = GameObject.Find("LW item Holder");
         _myTransform = transform;
         state = State.close;
 
         
 
     }
 
     // Update is called once per frame
     void Update () {
         if (!inUse)
         {
             return;
         }
 
         if (_player == null)
         {
             return;
         }
 
         if(Vector3.Distance(_myTransform.position, _player.transform.position) > maxDistance)
         {
             playerHUD.chest.ForceClose();
         }
         return;
     }
 
     public void OnMouseEnter()
     {
     }
 
 
     public void OnMouseExit()
     {
     }
 
 
     public void OnMouseUp()
     {
 
         GameObject go = GameObject.FindGameObjectWithTag("Player");
 
         if(go == null)
         {
             return;
         }
         if(Vector3.Distance(_myTransform.position, go.transform.position) > maxDistance && !inUse)
         {
             return;
         }
 
 
         switch (state)
         {
             case State.open:
                 state = State.inbetween;
                 ForceClose();
                 break;
             case State.close:
                 if(playerHUD.chest != null)
                 {
                     playerHUD.chest.ForceClose();
                 }
                 state = State.inbetween;
                 StartCoroutine("Open");
                 break;
         }
     }
 
     private IEnumerator Open()
     {
   //set this script to be the one that is holding the items
         playerHUD.chest = this;
 
   //find the player so its distance can be trcked after opening the chest
         _player = GameObject.FindGameObjectWithTag("Player");
 
         inUse = true;
 
         GetComponent<Animation>().Play("open");
         GetComponent<AudioSource>().PlayOneShot(openSound);
 
         if (!_used)
         {
         PopulateChest(5);
         }
 
    //wait until the chest is done opening
         yield return new WaitForSeconds(GetComponent<Animation>()["open"].length - .5f);
         state = State.open;
 
         Messenger.Broadcast("DisplayLoot");
     }
 
     private void PopulateChest(int x)
     {
 
         
         for (int cnt = 0; cnt < x; cnt++)
         {
             loot.Add(ItemGenerator.CreateItem());
             loot[cnt].Icon = Instantiate(loot[cnt].Icon);
    //         if (loot[cnt].Icon == null)
    //         {
     //            loot[cnt].Icon = Instantiate(item) as GameObject;
     //            loot[cnt].Icon.transform.SetParent(LWitemHolder.gameObject.transform, false);
     //        }
      //       loot[cnt].Name = "I:" + Random.Range(0, 100);
     //      item = Instantiate(item);
    //        item.transform.SetParent(LWitemHolder.transform, false);
            item.name = loot[cnt].Name;
         }
         _used = true;
         //      loot.ForEach((Item) => { Instantiate(item); });
           
 
 
     }
 
     private IEnumerator Close()
     {
         _player = null;
         inUse = false;
 
         GetComponent<Animation>().Play("close");
         yield return new WaitForSeconds(GetComponent<Animation>()["close"].length);
         GetComponent<AudioSource>().PlayOneShot(closeSound);
         state = State.close;
 
    //     for (int cnt = 0; cnt < loot.Count; cnt++)
    //     {
   //          Destroy(item);
   //      }
         
     }
 
     public void ForceClose()
     {
         Messenger.Broadcast("CloseChest");
 
         StopCoroutine("Open");
         StartCoroutine("Close");
 
     }
 
 
 
 }

The commented out code above is different things that only partially worked.

Comment
Add comment · Show 4
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 itsharshdeep · Dec 24, 2016 at 01:41 PM 0
Share

Hi,

As far I understand the question is that "You need to show the number of the buttons as per the items in the chest"

Now for the new UI you just need to do the same as we spawn the gameobject runtime. i.e.

  1. Drop the prefab of the UI button from the project( assets folder) or you can get it in runtime from the 'Resources' folder

  2. $$anonymous$$ake the button child to of the Canvas/UIPanel(Screen)/List_Of_Button ( in the Hierarchy)

  3. For better result use Vertical or Horizontal Layout Group, Content filter & layout element

References videos: https://www.youtube.com/watch?v=DAdW_$$anonymous$$44Dao https://www.youtube.com/results?search_query=horizontal+layout+group+unity

avatar image ShaggySlade itsharshdeep · Dec 24, 2016 at 06:13 PM 0
Share

Yes thats what Im trying to do....but i cannot make it work using the resources folder for some reason.

I have a layout group setup and it works as it should with the prefab I made.

Basically what Im trying to figure out is how to take the OnGUI system from these videos.... https://www.youtube.com/watch?v=9v8xXzbOcCo∈dex=132&list=PLE5C2870574BF4B06 ....And do it in UI

avatar image itsharshdeep ShaggySlade · Dec 24, 2016 at 07:05 PM 1
Share

If you are saying that code is working fine with the public reference & output is also acceptable then do check your Resources line ( line of code ) or the spelling mistakes of the folder.

Sorry if I am giving the lame/silly reasons I better know that you checked that twice but I think I'm not getting up to that point which led me to that direction in which I can suggest you any useful stuff :(

Show more comments

0 Replies

· Add your reply
  • Sort: 

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

129 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

Related Questions

UI Image Cutout / Masking in spefic areas with sprites 0 Answers

Issue adding animated sprite to UI Button 1 Answer

Smooth UI sprite animation. 1 Answer

Unity UI Problem 0 Answers

How to fix blur sprites and text in UI 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