Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 edd677 · Mar 13, 2015 at 04:12 PM · c#guienemyhealth

Enemy Health GUI Issues

Hi all,

I'll try to explain this as best as possible.

I am making a basic RPG in attempt to gain a better understanding of programming in Unity, and C#.

The Plan:

In the game, users can target a single enemy at a time. When an enemy is targeted, a health bar is displayed for that enemy only. Players can use KeyCode.Alpha1 to cast an spell (currently a simply sphere) that travels towards the targeted enemy, deals damage to that enemy ONLY, and is destroyed on impact. This projectile should deal

I have four scripts to support this system: Targeting, EnemyHealthSystem, PlayerAttack, and EnergyBlast.

I can select targets, and fire projectiles at the selected target, but I have encountered several problems:

  • Enemies appear to share one health pool.

  • Upon being hit by an energy blast, the health bar of the selected enemy disappears, even when the enemy is not deselected. The enemy remains selected however, but once shot, it's health bar is never seen again (whatever I try).

  • Unity keeps asking for an inspector reference to the public GameObject in Targeting, yet this is only set when a target is selected in-game. I feel it needs to be public so that that damage can be dealt to that particular enemy.

Thank you for your time, here are my scripts!

Targeting:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Targeting : MonoBehaviour 
 {
 
     private Transform selectedTarget;
     public GameObject enemyTarget;
 
 
     void Start()
     {
         selectedTarget = null;
         enemyTarget = selectedTarget.gameObject;
         
     }
 
     void Update()
     { 
         if (Input.GetMouseButtonDown(0))// when button clicked... 
         { 
             RaycastHit hit;
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // cast a ray from mouse pointer:
             if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Enemy"))// if enemy hit...
                 { 
                 DeselectTarget(); // deselect previous target (if any)...
                 selectedTarget = hit.transform; // set the new one... 
 
                 SelectTarget(); // and select it
                 
                 } 
             else
             {
                 DeselectTarget();
             }
         }
         else
         {
             return;
         }
 
         enemyTarget = selectedTarget.gameObject;
 
     }
             
     private void SelectTarget()
     { 
         selectedTarget.GetComponent<EnemyHealthSystem>().enabled = true;
         //PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
         //pa.target = selectedTarget.gameObject;
     }
             
     private void DeselectTarget()
     { 
         if (selectedTarget)
         { // if any target is selected, deselect it 
             selectedTarget.GetComponent<EnemyHealthSystem>().enabled = false;
             selectedTarget = null;
         } 
     }
 } 

EnemyHealthSystem

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class EnemyHealthSystem : MonoBehaviour {
     
     public int currentEnemyHealth;
     public int maxHealth = 100;
     public AudioClip skeletonHurtSound; // Sound when this enemy dies.
 
     public Texture enemyHealthBarTexture; // Only one texture needed (red), as no background
     
     private float lifeRatio; // % Of life remaining - used to set size of health bar
     private float lifeBarWidth; // Width of life bar.
     private float lifeBarHeight; // Height of life bar.
     private float lifeBackgroundWidth;
     private int healthBarLeft = 20;
     private Vector3 screenPosition;
     private Vector3 worldPosition;
     private int barTop = 3;
     private float adjustment = 2.3f;
     private Transform myTransform;
     private float distance;
     private Camera myCamera;
     private GameObject myCam;
     private bool inRange;
 
     private GameObject thePlayer;
     Targeting targeting;
 
     // Component References
     AudioSource enemyAudio;
     Animator anim;
     CapsuleCollider capsuleCollider;
     public bool isDead;
     //bool isFading;
 
 
     void Awake()
     {
 
         thePlayer = GameObject.Find("ThirdPersonController");
         targeting = thePlayer.GetComponent<Targeting>();
 
         myCam = GameObject.FindGameObjectWithTag("MainCamera"); //I removed the space from the camera's name in the Unity Inspector, so you will probably need to change this
         myCamera = Camera.main; 
 
         lifeBackgroundWidth = 30.0f;
         lifeBarHeight = 3.0f;
 
         myTransform = transform;
         enemyAudio = GetComponent<AudioSource>();
         //anim = GetComponent<Animator>();
         capsuleCollider = GetComponent<CapsuleCollider>();
         
         currentEnemyHealth = maxHealth;
         
         isDead = false;
 
     }
 
     void Update()
     {
         lifeRatio = currentEnemyHealth/maxHealth;
         lifeBarWidth = lifeRatio * lifeBackgroundWidth;
         
     }
 
 
     void OnGUI()
     {
         distance = Vector3.Distance(myCam.transform.position, transform.position); //gets the distance between the camera, and the intended target we want to raycast to
         if (distance < 25f)
         {
             inRange = true;
         }
         else
         {
             inRange = false;
         }
 
         worldPosition = new Vector3(myTransform.position.x, myTransform.position.y + adjustment,myTransform.position.z);
         screenPosition = myCamera.WorldToScreenPoint(worldPosition);
 
 
         //if something obstructs our raycast, that is if our characters are no longer 'visible,' dont draw their health on the screen.
         if (inRange && targeting.enemyTarget != null && targeting.enemyTarget.gameObject.transform == this.transform) //isSelected /* && isVisible*/)
         {
 
             GUI.DrawTexture(new Rect (screenPosition.x - healthBarLeft / 2.0f, Screen.height - screenPosition.y - barTop, lifeBarWidth, lifeBarHeight), enemyHealthBarTexture); //displays a healthbar
             
         }
         else{
             return;
         }
 
     }
 
     public void TakeDamage(int amount)
     {
         if (isDead)
             return;
         
         enemyAudio.Play();
         currentEnemyHealth -= amount;
         Debug.Log("My current health is " + currentEnemyHealth);
         
         if (currentEnemyHealth <= 0)
         {
             Death();
             targeting.enemyTarget = null;
         }
         
     }
 
     void Death()
     {
         //isDead = true;
         
         //capsuleCollider.isTrigger = true;
         
         //anim.SetTrigger ("Dead");
         
         // enemyAudio.clip = deathClip;
         //enemyAudio.Play ();
     }
 
     // Method to fade the enemies body away after a certain amount of time following its death.
     /* public void FadeAway()
     {
         GetComponent <NavMeshAgent>().enabled = false;
         GetComponent <Rigidbody>().isKinematic = true;
         isFading = true;
         Destroy(gameObject, 2f);
     }*/
 
 }
 

PlayerAttack

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;
 
 /// <summary>
 /// This Script will contain all the attacks available to the player. It will contain information about
 /// their costs, the damage of the attacks (to the target), and will control their animations.
 /// Attacks cost the player Arcane (or possibly later, energy) which will regenerate slowly.
 /// </summary>
 
 
 public class PlayerAttack : MonoBehaviour {
 
     GameObject thePlayer;
     PlayerStats playerStats;
 
     public Rigidbody EnergyBlast; // One off energy blast.
 
 
     void Awake()
     {
         thePlayer = GameObject.Find("ThirdPersonController");
         playerStats = thePlayer.GetComponent<PlayerStats>();
         
     }
 
     // Use this for initialization
     void Start ()
     {
 
     }
     
     // Update is called once per frame
     void Update ()
     {
 
 
         // Arcane Control
         if(playerStats.currentArcane >= 0)
         {
             playerStats.currentArcane += Time.deltaTime * playerStats.arcaneRegenRate;
         }
         
         // Spells. Number 1 is a one-off spell, number 2 is channeled spell.
         if (Input.GetKeyDown(KeyCode.Alpha1) && playerStats.currentArcane >= playerStats.arcaneCostSpell1 /*&& targeting.selectedTarget != null && enemyHealth.currentEnemyHealth > 0 && enemyHealth.isDead == false*/)
         {
             Instantiate(EnergyBlast);
             playerStats.currentArcane -= playerStats.arcaneCostSpell1;
             
         }
         
         if (Input.GetKey(KeyCode.Alpha2))
         {
             playerStats.currentArcane -= Time.deltaTime * playerStats.arcaneFallRateChannelling;
         }
 
     }
 }
 

EnergyBlast

 using UnityEngine;
 using System.Collections;
 
 public class EnergyBlast : MonoBehaviour {
 
     // Transforms to act as start and end markers for the journey.
     private Transform enemy;
     private Transform spellSpawn;
 
     // Reference to player so we can set starting transform of ability appropriately.
     GameObject thePlayer;
     GameObject spellSpawnCube;
 
     public int damagePerSpell;
     public float spellRange;
 
     // Movement speed of attack in units/sec.
     public float speed;
 
     // Time when the movement started.
     private float startTime;
 
     // Total distance between the player and the selected enemy.
     private float journeyLength;
 
     void Awake()
     {
         // Sets reference to player game object, so we can get transform.
         thePlayer = GameObject.FindGameObjectWithTag("Player");
         // Obtains and sets transform of 'enemy' to players selected target.
         enemy = thePlayer.GetComponent<Targeting>().enemyTarget.transform;
 
         // Sets location of spellSpawn to transform of spellSpawnCube.
         spellSpawnCube = GameObject.Find("SpellOrigin");
         spellSpawn = spellSpawnCube.transform;
         
     }
 
     // Use this for initialization
     void Start ()
     {
         // Keeps track of time the object was instantiated.
         startTime = Time.time;
 
         // Calculates the journey length the object will travel (distance between enemy and player).
         journeyLength = Vector3.Distance(spellSpawn.position, enemy.position);
     }
     
     // Update is called once per frame
     void Update () 
     {
         // Distance moved is equal to time * speed.
         float distCovered = (Time.time - startTime) * speed;
 
         // Fraction of journey completed = current distance divided by total distance.
         float fracJourney = distCovered / journeyLength;
 
         // Sets position of spell as a fraction of the distance between the player and enemy.
         transform.position = Vector3.Lerp (spellSpawn.position, enemy.position, fracJourney);
 
         // Code to allow object to curve.
         transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (enemy.transform.position - spellSpawn.position), 2 * Time.deltaTime);
         transform.rotation = Quaternion.LookRotation (enemy.position - spellSpawn.position) * Quaternion.AngleAxis (30, transform.up);
     }
 
     void OnTriggerEnter (Collider other)
     {
         if (other.gameObject.CompareTag("Enemy"))
         {
             Destroy(gameObject);
 
             EnemyHealthSystem enemyHealth = other.gameObject.GetComponent <EnemyHealthSystem>();
             if(enemyHealth != null)
             {
                 enemyHealth.TakeDamage(10);
             }
 
         }
     }
 
 }
 










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

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

2 People are following this question.

avatar image avatar image

Related Questions

Taking a hit 3 Answers

Multiple Cars not working 1 Answer

Deduct health on collision 2 Answers

how do i make an Enemy take damage from prefab bullet clone? 1 Answer

Make HUD to show object direction 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