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 /
This question was closed Jun 30, 2016 at 11:49 AM by Vekosava for the following reason:

The question is answered, right answer was accepted

avatar image
0
Question by Vekosava · Jun 28, 2016 at 12:49 PM · enemytargetingtimer countdowncombatcooldown

Attack timer stops after killing enemy (when attack script loose target)

Hey guys! I have a problem, I have attack script with cooldown and stuff in it, I've created basic combat system, everything works until I kill enemy, it destroys it as intended but then my attack timer stops counting until I select another enemy. Also I keep getting an error until I select first enemy because target field in attack script is empty at start.

Scripts:

Attack Script:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 
 public class BasicAttack : MonoBehaviour {
 
     public GameObject target; //target to attack
 
     public int damage;
 
     public float range = 4;
     public float attackTimer;
     public float cooldown = 2.0f;
 
     public GameObject damageNumber;
     public GameObject cooldownImage;
     public Text cooldownText;
 
     Targeting t;
     UserInterface UI;
 
     void Start () {
 
         cooldownImage.SetActive(false);
 
         attackTimer = 0;
 
         t = FindObjectOfType<Targeting>();
         UI = FindObjectOfType<UserInterface>();
     }
 
     void Update () {
         
         float distance = Vector3.Distance(target.transform.position, transform.position); //calculating distance
 
         cooldownText.text = attackTimer.ToString("F0");
     
         if (attackTimer > 0) {
             attackTimer -= Time.deltaTime;
         }
         if (attackTimer <= 0) {
             attackTimer = 0;
         }
         if (Input.GetKeyUp("1")) { //attack key
             if (attackTimer == 0 && distance < range) {
                 Attack();
                 attackTimer = cooldown;
                 //damage numbers
                 var clone = (GameObject)Instantiate(damageNumber, t.selectedTarget.GetComponent<EnemyAI>().hitPoint.position, t.myTransform.rotation);
                 clone.GetComponent<DamageNumbers>().damageNumber = damage;
             }
             else {
                 Debug.Log("Target is out of range!");
             }
         }
         else {
             cooldownImage.SetActive(true);
         }
 
         if (attackTimer == 0) {
             cooldownImage.SetActive(false);
         }
     }
 
     public void Attack() {
 
             float distance = Vector3.Distance(target.transform.position, transform.position); //calculating distance
 
             Vector3 dir = (target.transform.position - transform.position).normalized; //calculating direction
             float direction = Vector3.Dot(dir, transform.forward); //calculating direction
 
             if (distance < range) { //making player not be able to attack if too far
 
                 if (direction > 0) { //making player not be able to attack if target not in front of him
                     EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth"); //getting enemy health
                     t.selectedTarget.GetComponent<EnemyHealth>().TakeDamage(-damage); //adjusting enemy health
 
                     UI.infoText.text = "";
                 }
                 else {
                     Debug.Log("Target needs to be in front of you!");
                 }
                 UI.infoText.text = "";
             }
             else {
                 Debug.Log("Target is out of range!");
             }
     } //attack
 }

EnemyHealth Script:

 using UnityEngine;
 using System.Collections;
 
 public class EnemyHealth : MonoBehaviour {
     
     public float maxHealth = 100;
     public float curHealth = 100;
 
     CombatTargetUI ct;
 
     void Start () {
         ct = FindObjectOfType<CombatTargetUI>();
     }
 
     void Update () {
         TakeDamage(0);
     }
 
     public void TakeDamage (int ad) {
         curHealth += ad;
 
         if (curHealth <= 0) {
             curHealth = 0;
             /*ct.HideUI();*/
             Die();
         }
         if (curHealth >= maxHealth) {
             curHealth = maxHealth;
         }
         if (maxHealth <= 1) {
             maxHealth = 1;
         }
     }
 
     void Die () {
         
         StartCoroutine(TimeToDestroy());
     }
 
     IEnumerator TimeToDestroy () {
         yield return new WaitForSeconds(0.5f);
         ct.HideUI();
         Destroy(gameObject);
     }
 }

Targeting Script:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Targeting : MonoBehaviour {
 
     public List<Transform> targets;
     public Transform selectedTarget;
 
     public Transform myTransform;
 
     CombatTargetUI ct;
 
     void Start () {
         targets = new List<Transform>();
         selectedTarget = null;
         myTransform = transform;
 
         ct = FindObjectOfType<CombatTargetUI>();
 
         AddAllEnemies();
     }
 
     public void AddAllEnemies () {
 
         GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
 
         foreach (GameObject enemy in go) {
             AddTarget(enemy.transform);
         }
     }
 
     public void AddTarget (Transform enemy) {
         targets.Add(enemy);
     }
 
     void SortTargetsByDistance () {
         
         targets.RemoveAll(target => target == null);
         targets.Sort(delegate(Transform t1, Transform t2) {
             return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
                 });
     }
 
     void TargetEnemy () {
 
         if (selectedTarget == null) {
             SortTargetsByDistance();
             selectedTarget = targets[0];
         }
         else {
             int index = targets.IndexOf(selectedTarget);
 
             if (index < targets.Count - 1) {
                 index++;
             }
             else {
                 index = 0;
             }
             DeselectTarget();
             selectedTarget = targets[index];
         }
         SelectTarget();
     }
 
     void SelectTarget () {
 
         ct.ShowUI();
 
         selectedTarget.GetComponent<Renderer>().material.color = Color.red;
 
         BasicAttack ba = (BasicAttack)GetComponent("BasicAttack");
         ba.target = selectedTarget.gameObject;
     }
 
     public void DeselectTarget () {
         if (selectedTarget != null) {
             selectedTarget.GetComponent<Renderer>().material.color = Color.white;
         }
 
         selectedTarget = null;
     }
 
     void Update () {
 
         if (Input.GetKeyDown(KeyCode.Tab)) {
             TargetEnemy();
         }
     }
 }

I think that those are all scripts that might cause problem, can anyone help me? I'm desperate. :(

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

1 Reply

  • Sort: 
avatar image
0

Answer by PrisVas · Jun 28, 2016 at 04:59 PM

Always check if target isn't null.

 if (target)
 {
        float distance = Vector3.Distance(target.transform.position, transform.position); 
 }



Comment
Add comment · Show 3 · 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 Vekosava · Jun 29, 2016 at 02:15 PM 0
Share

This doesn't work. :( It gives an error because when I write and if check, code can't find "distance" variable.

avatar image PrisVas Vekosava · Jun 29, 2016 at 02:24 PM 1
Share

Well... Everything that depends on the target or distance of the target, put into the check.

avatar image Vekosava PrisVas · Jun 30, 2016 at 11:48 AM 0
Share

Got it, thanks!

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Character continues moving when locked onto an enemy 1 Answer

Homing Missile targetting the nearest Enemy 1 Answer

Player inCombat state problem 0 Answers

Switching Target 0 Answers

Enemy combat help 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