Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 /
avatar image
0
Question by patrick-holder · Aug 13, 2014 at 01:12 AM · getcomponentontriggerenter

How can I increase Health Value on trigger enter, to another game object?

I'm new to coding so I'm wasting hours on end trying to figure this out.

I want to add +1 Health to other gameobject (which has Health script attached and controls gameover etc) when the Player gameobject collides with a coin/collectable.

Can somebody help?

This is what I have so far:

using UnityEngine; using System.Collections;

public class SendHealthToPlayer : MonoBehaviour {

 public int healthValue;
 private Health triggerforattackbounds;


 void Start ()
 {
     GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("Player");
     if (gameControllerObject != null)
     {
         triggerforattackbounds = gameObject.GetComponent <Health>();
     }
     if (triggerforattackbounds == null)
     {
         Debug.Log ("Cannot find 'Triggerforattackbounds' script");
     }
 }

 void OnTriggerEnter (Collider other)
 {
     if (other.gameObject.tag == "Player")
     {
         Health triggerforattackbounds = other.GetComponent<healthValue>.currentHealth += 1();
     }
 }

}

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

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by robertbu · Aug 13, 2014 at 01:15 AM

You are pretty close. Line 22 should be:

   other.GetComponent<Health>().currentHealth += 1;

This assumes that the name of the script for health on the player is 'Health' and that the variable that stores the health is 'currentHealth'. I cannot tell what the name you use for the script that has 'currentHealth' in it. Note the first formatted line can be deleted.

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
avatar image
0

Answer by zee_ola05 · Aug 13, 2014 at 01:16 AM

This

 Health triggerforattackbounds = other.GetComponent<healthValue>.currentHealth += 1();


should be

 Health triggerforattackbounds = other.GetComponent<healthValue>().currentHealth += 1;
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
avatar image
0

Answer by patrick-holder · Aug 13, 2014 at 10:29 AM

Thanks for your answers but this give the Playermodel that is controlled +1 Health but not the gameobject called "triggerforattackbounds" which controls gameover etc... They are both tagged "Player", is this the wrong way of doing it or can I give both objects +1 Health?

This is the Health Script on "triggerforattackbounds" which I added bit to:

public class Health : MonoBehaviour { public AudioClip GameOver; public AudioClip impactSound;
public AudioClip hurtSound;
public AudioClip deadSound;
public int currentHealth = 3;
public bool takeImpactDmg;
public bool onlyRigidbodyImpact;
public bool respawn;
public string[] impactFilterTag;
public float hitFlashDelay = 0.1f;
public float flashDuration = 0.9f;
public Color hitFlashColor = Color.red;
public Transform flashObject;
public GameObject[] spawnOnDeath;
public PauseManager pauseManager;

 string message = string.Empty;
 
 [HideInInspector]
 public bool dead, flashing;
 [HideInInspector]
 public Vector3 respawnPos;
 
 private Color originalColor;
 private int defHealth, h, hitForce;
 private bool hitColor = false;
 private float nextFlash, stopFlashTime;
 private Throwing throwing;
 
 //setup
 void Awake()
 {
     if(currentHealth <= 0)
         Debug.LogWarning(transform.name + " has 'currentHealth' set to 0 or less in 'Health' script: it has died upon scene start");
     audio.playOnAwake = false;
     if(flashObject == null)
         flashObject = transform;
     originalColor = flashObject.renderer.material.color;
     defHealth = currentHealth;
     respawnPos = transform.position;
     obj.Volume = 0.4f;
 }
 
 //detecting damage and dying
 void Update()
 {        
     //flash if we took damage
     if (currentHealth < h)
     {
         flashing = true;
         stopFlashTime = Time.time + flashDuration;
         if (hurtSound)
             AudioSource.PlayClipAtPoint(hurtSound, transform.position);
     }
     h = currentHealth;
     
     //flashing
     if (flashing)
     {
         Flash ();
         if (Time.time > stopFlashTime)
         {
             flashObject.renderer.material.color = originalColor;
             flashing = false;
         }
     }
     
     //are we dead?
     dead = (currentHealth <= 0) ? true : false;
     if (dead)
     {
         ResultManager.Instance.ShowResultBox(true,Random.Range(1,4),new CallbackFunction[]{DoReplay});
         AudioSource.PlayClipAtPoint(GameOver, Camera.main.transform.position);
         Time.timeScale = 0;
         obj.Volume = 0.0f;
         Destroy(pauseManager);

     }
 }
 void DoReplay()
 {
     message = "Click replay button";
 }
 
 //toggle the flashObject material tint color
 void Flash()
 {
     flashObject.renderer.material.color = (hitColor) ? hitFlashColor : originalColor;
     if(Time.time > nextFlash)
     {
         hitColor = !hitColor;
         nextFlash = Time.time + hitFlashDelay;
     }
 }
 
 //respawn object, or destroy it and create the SpawnOnDeath objects
 void Death()
 {
     //player drop item
     if(tag == "Player")
         throwing = GetComponent<Throwing>();
     if(throwing && throwing.heldObj && throwing.heldObj.tag == "Pickup")
         throwing.ThrowPickup();
     
     if (deadSound)
         AudioSource.PlayClipAtPoint(deadSound, transform.position);
     flashing = false;
     flashObject.renderer.material.color = originalColor;
     if(respawn)
     {
         if(rigidbody)
             rigidbody.velocity *= 0;
         transform.position = respawnPos;
         dead = false;
         currentHealth = defHealth;
     }
     else
         Destroy (gameObject);
     
     if (spawnOnDeath.Length != 0)
         foreach(GameObject obj in spawnOnDeath)
             Instantiate(obj, transform.position, Quaternion.Euler(Vector3.zero));
 }
 
 //calculate impact damage on collision
 void OnCollisionEnter(Collision col)
 {
     if(!audio.isPlaying && impactSound)
     {
         audio.clip = impactSound;
         audio.volume = col.relativeVelocity.magnitude/30;
         audio.Play();
     }
     
     //make sure we take impact damage from this object
     if (!takeImpactDmg)
         return;
     foreach(string tag in impactFilterTag)            
         if(col.transform.tag == tag)
             return;
     if(onlyRigidbodyImpact && !col.rigidbody)
         return;
     
     //calculate damage
     if(col.rigidbody)
         hitForce = (int)(col.rigidbody.velocity.magnitude/4 * col.rigidbody.mass);
     else
         hitForce = (int)col.relativeVelocity.magnitude/6;
     currentHealth -= hitForce;
     //print (transform.name + " took: " + hitForce + " dmg in collision with " + col.transform.name);
 }

}

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Collection Using "GetComponent" 1 Answer

Damager Powerup issue - NullReferenceException: Object reference not set to an instance of an object 2 Answers

Setting thrown object to kinematic after hitting target? 1 Answer

Updating GUIText 3 Answers

Need help with get child component script 1 Answer


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