Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Bridging the Gender Gap: Inspiring Words from the Women Making Waves on Starship | Annie Handrick | | Starship Technologies | March 2023

    March 8, 2023

    AI apps like ChatGPT may finally kill the cover letter

    March 8, 2023

    Snow Crash author Neal Stephenson on the metaverse, making movies, climate fears

    March 6, 2023
    Facebook Twitter Instagram
    • Home
    • About us
    • Contact us
    • Dmca
    • Privacy Policy
    Facebook Twitter Instagram Pinterest VKontakte
    Honest Coupon DealsHonest Coupon Deals
    • Home
    • Amazon

      Best new movies on Amazon Prime Video in February 2023

      February 2, 2023

      OSHA cites Amazon facility in upstate New York as safety breach

      February 2, 2023

      The end of ‘Amazon Smile’ means implications for local nonprofits

      February 2, 2023

      Amazon workers in Barcelona go on strike over warehouse closures

      February 2, 2023

      How Amazon Prime Members Can Get 20% Off Your Next Grubhub Purchase

      February 2, 2023
    • Codes

      Is Instagram Considering Paid Verification? Code Reveals References To ‘Paid Blue Badge’ TechCrunch

      February 2, 2023

      Compare Louisiana Civil Homeowner Insurance Rates by ZIP Code

      February 2, 2023

      Get $1000 Bonus Now

      February 2, 2023

      All Available Locker Codes (February 2023)

      February 2, 2023

      Berry Avenue Code (February 2023)

      February 2, 2023
    • Coupons

      Genius Group shares surge 40% on coupon offer for shareholders

      February 2, 2023

      Genius Group shares surge 40% on coupon offer for shareholders

      February 2, 2023

      GNS Stock Alert: $10 NFT Coupon Sends Genius Group Soaring

      February 2, 2023

      Woman scammed out of Rs 3.79 lakh by cyber crooks under the pretext of offering prize coupons

      February 2, 2023

      Adani Ports Coupon Bonds Expiring Today Now Yield 10%

      February 2, 2023
    • Makeup Deals

      I brought you TJ Maxx – 5 makeup items, including eyelashes you can’t find anywhere else, at huge discounts from big brands

      January 24, 2023

      I brought you TJ Maxx – 5 makeup items, including eyelashes you can’t find anywhere else, at huge discounts from big brands

      January 24, 2023

      Shop Nordstrom’s Half Year Sale — Save Up To 60% Off!

      December 31, 2022

      Nordstrom half year sale is here!Extra 25% Off Select Clearance Styles

      December 29, 2022

      From ‘magic’ highlighters to shopper-favorite hair growth kits, these are the 17 best beauty deals after Christmas

      December 28, 2022
    • Online Deals

      Men’s Gloves At Just $6: A Roundup Of The Incredible Online Sales For Feb 2, 2023

      February 2, 2023

      5 Best Pet Products to Buy at Costco This February

      February 2, 2023

      Wayfair’s ‘Big Furniture Sale’ offers great deals on sofas, tables, beds and more

      February 2, 2023

      Wayfair’s ‘Big Furniture Sale’ offers great deals on sofas, tables, beds and more

      February 2, 2023

      Ryan Reynolds is in Toronto wowing students at his local campus

      February 1, 2023
    • Walmart

      Walmart shoppers rage over self-checkout fears after ‘hundreds of arrests’ and rumors of closure amid burglary surge

      February 2, 2023

      Walmart AMP Welcomes Bryan’s Country On Tour | Arts & Entertainment

      February 2, 2023

      CVS, Walmart suing over homeopathic products. what are they?

      February 2, 2023

      Found apparel items for just 3 cents at Walmart Hidden Clearance even though they were listed for $4

      February 2, 2023

      Best deals at Walmart this week ahead of Valentine’s Day 2023: Apple, Dyson, Samsung TVs and more

      February 2, 2023
    Honest Coupon DealsHonest Coupon Deals
    Home»Codes»How to design and code a health bar in Unity3D
    Codes

    How to design and code a health bar in Unity3D

    honestcoupondeals_h8tsyfBy honestcoupondeals_h8tsyfJanuary 21, 2023No Comments6 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Pioneered in some of the world’s earliest video games, health is a common mechanic that carries over into many of today’s most popular titles. Health allows for complex combat mechanics, crafting player progression, and making the game more intuitive. But how do you add a health system to your game?


    Unity3D makes it easy to add 2D UI elements to your 3D game, so it’s a great place to start exploring health bars for the first time.


    content of study

    On the surface, this project may not look complicated. Still, you need to understand some core Unity3D coding concepts to create a valid health bar. This means that there is a lot to learn through this project.

    • How to create 2D UI elements/sprites in Unity3D.
    • How to edit game object components in code.
    • How to share variables between scripts in Unity3D.

    Step 1: Set the Scene

    Before we start coding our health bar, we need a scene with a player model to apply it to. To get started, follow his physics-based Unity3D character controller guide to create a player model with basic controls.

    With the scene and player model in place, it’s time to add the UI elements. Right-click inside the Hierarchy window and select UI > imageThis creates two new items in the hierarchy, a Canvas parent object and an Image child object. Rename the child object to Healthbar. Use the inspector to choose the width, height, and position of the health bar.

    Unity add ui images

    You can add a slightly larger UI image with color set to black to act as a background/border for the health bar. Make sure it’s above the health bar in the hierarchy so it appears behind it.

    This UI element serves as the basis for the health bar, but we also need a sprite to animate it. Go to your project pane, right click, create > Two dimensions > sprite > square.

    Unity add new sprite

    Select Healthbar from the hierarchy and drag the sprite you just created onto the source image selection box in the inspector.You can also change Image type filled, Fill method horizontally and fill origin to the left.run the game Loading You should see the health bar shrink and expand as you move the slider.

    Add sprites as object components

    If you don’t see the UI component menu, Window > Package Managermake sure the 2D pack is installed.

    Step 2: Add Health Variables

    It doesn’t make much sense to create a health bar without putting a health variable to dictate the state. Other scripts need to be able to access this variable, so it makes sense to put it in a central location. Add this to your Character Control script as a public float.

     public float playerHealth = 1.0f;

    Using a float for this variable makes it easy to represent any percentage between 0 and 100, matching the Fill Amount variable in the health bar UI image. For example, a playerHealth of 0.5f is 50% of the width of the health bar.

    Step 3: Share variables between scripts in Unity

    Variables typically work within their own functions and scripts. This makes them inaccessible to other functions and scripts unless you take steps to tell your code where to work with variables.

    First, create a new script file named Health to contain your code. You can drag and drop this script onto the Healthbar UI element created in the first step. The following code goes into the void Update() function.

    The process begins by finding the game object that owns the variable. In this case, it’s a Character_Model object.

     GameObject Character_Model = GameObject.Find("Character_Model");

    Then find the script component that contains the variable you need to manipulate.

     Character_Control character_Control = Character_Model.GetComponent();

    Finally, you can extract the specific variable you’re looking for. In this case, it’s the playerHealth variable we added to the character controller. Assign this to a float variable in the current script called currentHealth.

     currentHealth = character_Control.playerHealth;

    It takes only a few lines of code to get the variables we need and we can apply this method whenever we need to access the player’s health. When you’re done, your code should look like this:

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

    public class Health : MonoBehaviour
    {
        public float currentHealth;

        void Start()
        {
        }

        void Update()
        {
            GameObject Character_Model = GameObject.Find("Character_Model");
            Character_Control character_Control = Character_Model.GetComponent();
            currentHealth = character_Control.playerHealth;
        }
    }

    Step 4: Program the UI Health Bar Game Object

    Now that you have created the health bar UI element and have access to the player’s health variables, it’s time to make them work together. First, add a private static variable containing the health bar image component.

     private static Image Healthbar;

    You can then assign the image component to this variable within the void Start() function, which runs only once.

     Healthbar = GetComponent();

    With all the variables in place, we can use the code from the previous step to set the fill width of the health bar UI object. No need to perform any conversion here. Both player health and health bar fill amount are float variables.

     Healthbar.fillAmount = currentHealth;

    Placing this code will raise or lower the health bar based on the health variable found in the Character_Control code. However, this is a little boring. You can definitely use some colors.

    First, we’re adding a new color to make the health bar bright green when the player has high health.

     Color greenHealth = new Color(0.6f, 1, 0.6f, 1);

    Next, add an if statement to check if the player’s health is above 0.3f, or above 30%. If it’s higher than 0.3f, set the health bar to match the color you just added. If it’s less than 0.3f, make the health bar red.

     if (currentHealth >= 0.3f) {
        Healthbar.color = greenHealth;
    } else {
        Healthbar.color = Color.red;
    }

    Step 5: Test Your Code

    As you can see from the full code below, this project is pretty simple when everything is put together. Of course, you need a way to test your code.

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

    public class Health : MonoBehaviour
    {
        private static Image Healthbar;
        public float currentHealth;

        void Start()
        {
            Healthbar = GetComponent();
        }

        void Update()
        {
            GameObject Character_Model = GameObject.Find("Character_Model");
            Character_Control character_Control = Character_Model.GetComponent();
            currentHealth = character_Control.playerHealth;
            Healthbar.fillAmount = currentHealth;

            Color greenHealth = new Color(0.6f, 1, 0.6f, 1);

            if (currentHealth >= 0.3f) {
                Healthbar.color = greenHealth;
            } else {
               Healthbar.color = Color.red;
           }
        }
    }

    You can add one line of code to the Character_Control script to enable testing. Removes a small amount of health each time the player presses his W key to move forward. You can add the same code to any script that has access to the playerHealth variable to achieve the same result.

     playerHealth -= 0.001f;

    You can also consider adding your own assets to your Unity project. You can find free Unity assets on the web to spice up your project without spending a dime.

    Create a health bar in Unity3D

    Now that your character’s health bar is set, the game is starting to take shape. You still have a lot of work to do, but you should have some key skills you need to really make progress. Of course, it doesn’t hurt to read more guides.



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    honestcoupondeals_h8tsyf
    • Website

    Related Posts

    Is Instagram Considering Paid Verification? Code Reveals References To ‘Paid Blue Badge’ TechCrunch

    February 2, 2023

    Compare Louisiana Civil Homeowner Insurance Rates by ZIP Code

    February 2, 2023

    Get $1000 Bonus Now

    February 2, 2023

    All Available Locker Codes (February 2023)

    February 2, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Editors Picks

    Bridging the Gender Gap: Inspiring Words from the Women Making Waves on Starship | Annie Handrick | | Starship Technologies | March 2023

    March 8, 2023

    AI apps like ChatGPT may finally kill the cover letter

    March 8, 2023

    Snow Crash author Neal Stephenson on the metaverse, making movies, climate fears

    March 6, 2023

    A new era of tech coverage at Vox

    March 6, 2023
    Top Reviews
    9.1

    Review: Mi 10 Mobile with Qualcomm Snapdragon 870 Mobile Platform

    By Mohamad Fiverr
    8.9

    Comparison of Mobile Phone Providers: 4G Connectivity & Speed

    By Mohamad Fiverr
    8.9

    Which LED Lights for Nail Salon Safe? Comparison of Major Brands

    By Mohamad Fiverr
    Advertisement
    Honest Coupon Deals
    Facebook Twitter Instagram Pinterest Vimeo YouTube
    • Home
    • About us
    • Contact us
    • Dmca
    • Privacy Policy
    © 2023 honestcoupondeals. Designed by honestcoupondeals.

    Type above and press Enter to search. Press Esc to cancel.