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 Kun-No-Name · Mar 01, 2016 at 03:04 PM · scripting problemgameobjectvariable

How to change value of another gameobject through script

alt text

From the picture I upload, I tried to create a game control by mouse. When I click on the red box, its HP will decrease. I want to know how to change the value of ONLY red box that I click. I tried to control with scipt but it was decrease all of the red box.

this is the code attach to purple box.

 public class HPbarScript : MonoBehaviour {
 
     public Camera cam;
     public float MaxHealth = 100f;
     public float CurrentHealth = 0f;
     public float PercentHealth;
     public GameObject healthBar;
     public GameObject healthCanvas;
     
     public bool clickCooldown = false;
     
     void Start ()
     {
         CurrentHealth = MaxHealth;
         
     }
     
     
     void Update ()
     {
         healthCanvas.transform.LookAt(healthCanvas.transform.position + cam.transform.rotation * Vector3.back, cam.transform.rotation * Vector3.down);
         if(Input.GetMouseButtonDown(0))
         {
             if(clickCooldown == false)
             {
                 CalculateHP();
                 clickCooldown = true;
                 Invoke("Example", 1.0f);
             }
         }        
     }
     
     void Example()
     {
         clickCooldown = false;
     }
 
     void CalculateHP()
     {
         
         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         RaycastHit hitData;
         
         if (Physics.Raycast(ray, out hitData))
         {
             if(hitData.collider.gameObject.tag == "NPC")
             {
                 CurrentHealth -= 10f;
                 PercentHealth = CurrentHealth / MaxHealth;
                 healthBar.transform.localScale = new Vector3(Mathf.Clamp(PercentHealth,0f,1.0f), healthBar.transform.localScale.y, healthBar.transform.localScale.z);
                 
             }
             else if(hitData.collider.gameObject.tag == "Enemy")
             {
                 
             }
         }
    }
 
 }
 

sorry for my bad language.

1.png (251.7 kB)
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

2 Replies

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

Answer by EmHuynh · Mar 01, 2016 at 03:18 PM

Hello, Kun No Name.

Problem:

Each instances of the HPbarScript component are decreasing its own CurrentHealth variable when an enemy object is clicked.

Solution:

Get the HPbarScript component from the game object of hitData.collider. Then decrease the CurrentHealth variable of the component.

 else if( hitData.collider.gameObject.tag == "Enemy" ) {
     hitData.collider.gameObject.GetComponent< HPbarScript >().CurrentHealth -= 10f;
 }

Tip:

One of the best practices is to use the least amount of rays to get the job done. For every HPBarScript component in your scene, Physics.Raycast is being called when the left mouse button is clicked. That is inefficient.

A more efficient approach is to create a separate script to handle the job - using a single ray. Here is an example:

 using UnityEngine;
 using System.Collections;
 
 public class QA : MonoBehaviour
 {
     void Update()
     {
         if( Input.GetMouseButtonDown( 0 ) ) {
             Attack();
         }
     }
     
     void Attack()
     {
         Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
         RaycastHit raycastHit;
 
         if( Physics.Raycast( ray, out raycastHit ) )
         {
             if( raycastHit.collider.gameObject.tag == "Enemy" )
             {
                 raycastHit.collider.gameObject.GetComponent< HPbarScript >().CurrentHealth -= 5f;
             }
         }
     }
 }

Attach that script to an object that has only one instance. You can also create an empty game object and attach the script to it.

You can also make the CalculateHP function static, but we will need to make some small changes. Example:

 void ReduceHP( float damage ) {
     CurrentHealth -= damage;
     PercentHealth = CurrentHealth / MaxHealth;
     healthBar.transform.localScale = new Vector3(
         Mathf.Clamp( PercentHealth,
                      0f,
                      1.0f ),
         healthBar.transform.localScale.y,
         healthBar.transform.localScale.z );
 }
 
 static void CalculateHP()
 {
     Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
     RaycastHit hitData;
 
     if( Physics.Raycast( ray, out hitData ) )
     {
         float amount;
         switch( hitData.collider.gameObject.tag ) {
             case "NPC":    amount = 5f;    break;
             case "Enemy":  amount = 10f;   break;
             default:       amount = 0f;    break;
         }
     
         if( amount > 0 )
         { hitData.collider.gameObject.GetComponent< HPbarScript >().ReduceHP( amount ); }
     }
 }

Comment
Add comment · Show 1 · 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 Kun-No-Name · Mar 02, 2016 at 09:29 AM 0
Share

It work! Thanks man.

avatar image
0

Answer by NoseKills · Mar 01, 2016 at 03:26 PM

This is your health bar script. It's attached to all 4 prefabs. When you click, all 4 health bar scripts do the same check: if clicked on tag 'NPC', reduce health of this health bar ('this' meaning the health bar doing the check == all health bars)

You need to either separate the clicking code and tag-checking to a separate script that then tells only the hit cube's healthbar reduces health. Or just make your current script check whether it is attached to the cube that got clicked and only then reduce health.

Just be careful. hitData.collider.gameObject is the clicked cube, but you need to find its healthbar script from its children since that's where your health is stored.

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

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Destroyed instance of Prefab, can't spawn it back. 1 Answer

Changing a Prefab's Text component seems to be broken. 1 Answer

Script uses GameObject created in other Script 0 Answers

NullRefrenceException: Object refrence not set to an instance of an object. 0 Answers

I have a character object type that I want to make into a game object 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