• 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 /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by primus88 · Jun 05, 2013 at 05:05 PM · healthbar

What is wrong with this code ?

Hereunder is he health bar code I have for my units (a green bar floating above the units - RTS style). The problem is that the bar does not stick to the unit (or move together with it). In the second i move the camera the health bar moves in that direction.

Can you please help ?

     using UnityEngine;
     using System.Collections;
      
      
     public class AIHealth : MonoBehaviour {
     public int maxHp;
     public int currentHp;
     public Camera mainCamera;
     public Texture2D hpBarBG;
     public Texture2D hpBarCurrent;
         public Transform target; 
      
     private float offsetY;
      
     //script will be atached to each GameObject that can suffer dmg.
     void Start () {
     //put it on top of the character
     offsetY=gameObject.collider.bounds.size.y-2;
     Debug.Log(offsetY);
     }
      
     void Update () {
             health h=(health)GetComponent("health");
             h.currenthealth = currentHp;
             h.maxhealth = maxHp;
             var wantedPos = Camera.main.WorldToViewportPoint (target.position);
          transform.position = wantedPos; 
     }
      
     void OnGUI(){
     //the hp bar background location on screen
     Rect rcBg = new Rect(0,0,60,14);
     //the current HP bar
     Rect rcCurrent = new Rect(0,0,((currentHp)/maxHp)*56,8);
      
     //the important part : where this object is located in my screen
     Vector3 point = mainCamera.WorldToScreenPoint(new Vector3(
     transform.position.x,
     transform.position.y+offsetY,
     transform.position.z)
     );
      
     //had to add the substraction since my Y axis were revesed (
     rcBg.y = Screen.height-point.y;
      
     //do some ugly hardcoding so the bar is pretty and centered
     rcBg.x = point.x-30;
     rcCurrent.x=rcBg.x+2;
     rcCurrent.y=rcBg.y+3;
     GUI.DrawTexture(rcBg,hpBarBG);
     GUI.DrawTexture(rcCurrent,hpBarCurrent);
      
     }
      
     }
Comment
Add comment · Show 2
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 primus88 · Jun 05, 2013 at 08:24 PM 0
Share

No one can help ?

avatar image Mr-JWolf809 · Jun 05, 2013 at 09:53 PM 0
Share

Is it possible you could post your "health" class too.

Or even better. Create a small unity project only containing the nessersary files that shows the problem. I can't seem to get your code to work, and not sure what you had in $$anonymous$$d.

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Chronos-L · Jun 06, 2013 at 07:38 AM

The combination of these lines is creating the problem:

 var wantedPos = Camera.main.WorldToViewportPoint (target.position);
 transform.position = wantedPos; 
 
 ...
 
 //the important part : where this object is located in my screen
 Vector3 point = mainCamera.WorldToScreenPoint(new Vector3(
 transform.position.x,
 transform.position.y+offsetY,
 transform.position.z)
 );

The calculation, setting the transform.position to a viewportPoint, doesn't makes sense to me. I clean up some of the lines, attached the script to a simple cube, and I got a working health bar right under the cube.

 using UnityEngine;
 using System.Collections;
 
 public class AIHealth : MonoBehaviour {
     public int maxHp;
     public int currentHp;
     public Texture2D hpBarBG;
     public Texture2D hpBarCurrent;
     
     private float offsetY;
     
     void Start () {
         offsetY=gameObject.collider.bounds.size.y-2;
     }
     
     void Update () {
         //I commented these 3 lines out when I tested it
         health h=(health)GetComponent("health");
         h.currenthealth = currentHp;
         h.maxhealth = maxHp;
         
         //Removed the 2 line here, they are screwing things up
     }
     
     void OnGUI(){
         Rect rcBg = new Rect(0,0,60,14);
         
         //Fixed this: added in the 1.0f to correct the calculation
         Rect rcCurrent = new Rect(0,0,((currentHp)*1.0f/maxHp)*56,8);
         
         //Just a simple clean up
         Vector3 point = Camera.main.WorldToScreenPoint(
             transform.position + Vector3.up * offsetY
         );
         
         //Everything else are the same from here on
         ...
     }
 }
Comment
Add comment · Show 8 · 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 primus88 · Jun 06, 2013 at 07:54 AM 0
Share

I receive each frame :

NullReferenceException UnityEngine.Camera.WorldToScreenPoint (Vector3 position) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:327) AIHealth.OnGUI () (at Assets/$$anonymous$$yScripts/AIHealth.cs:32)

FOR :

Vector3 point = Camera.main.WorldToScreenPoint(transform.position + Vector3.up * offsetY);

I attached the script to my unit.

avatar image Chronos-L · Jun 06, 2013 at 08:00 AM 0
Share

Do you have a legit main camera in your scene?

http://docs.unity3d.com/Documentation/ScriptReference/Camera-main.html

avatar image primus88 · Jun 06, 2013 at 08:02 AM 0
Share

I forgot that I have to attach a camera because using the default setting wouldn't find my camera... Yeah I sorted it out. It looks ok now. Still doing some tests.

avatar image primus88 · Jun 06, 2013 at 08:10 AM 0
Share

Ok, works almost perfect. Why almost ? Because it works great if I attach the script to an existent game object, but if I do the same thing by attaching it to a prefab then spawning it, if the spawned objects move, the hb doesn't. It remain in the same place.

Help ?

avatar image Chronos-L · Jun 06, 2013 at 09:35 AM 0
Share

if I do the same thing by attaching it to a prefab then spawning it, if the spawned objects move, the hb doesn't.

I wrote a simple script to do the same and it is working fine at my machine, I can spawn a tons of object and move them anywhere I want and there is no problem.

It remain in the same place.

Is there any runtime error?

Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

16 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

NullReferenceException: Object reference not set to an instance of an object... 0 Answers

Health subtracts when hit by bullit 2 Answers

Healt Bar Logic 1 Answer

Screen.width ~ HealthBar problem - C# 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