private void OnTriggerEnter2D(Collider2D collider) { if (collider.tag.Equals(targetTag)) { UnitControls targetScript = collider.GetComponent <UnitControls>(); targetScript.TakeDamage(damage); Destroy(this.gameObject); } }
private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.tag == targetTag) { UnitControls enemyScript = collision.collider.GetComponent <UnitControls>(); enemyScript.TakeDamage(damage); Destroy(this.gameObject); } else { Destroy(this.gameObject); } }
IEnumerator ApplyDamage(UnitControls enemy, float cooldown, bool shouldMove) { isMoving = shouldMove; isAttacking = true; while (enemy != null) { yield return(new WaitForSeconds(cooldown)); if (gameObject != null && enemy != null) { enemy.health -= damage; enemy.healthBar.SetHealth(enemy.health, enemy.unitData.health); enemy.animator.SetTrigger("Damaged"); } } isMoving = true; isAttacking = false; yield return(null); }
IEnumerator EnemySpawner(float time) { while (true) { yield return(new WaitForSeconds(time)); if (UnityEngine.Random.Range(0f, 1f) < towerTurretSpawnChance) // adding random tower/turret spawning { SpawnTowerOrTurret(towerTurretChances); } bool shouldSpawn = UnityEngine.Random.Range(0f, 1f) < spawnChance; // adding randomness to spawning if (shouldSpawn && cooldown <= 0) { int index = GetIndexFromChances(chances, 0); // generate random index according to chances array if (units[index].cost <= gold) { Unit currentUnit = units[index]; cooldown = currentUnit.trainingTime; // creating enemy unit GameObject and assigning various variables GameObject enemy = new GameObject("Enemy" + currentUnit.name, typeof(UnitControls), typeof(SpriteRenderer), typeof(BoxCollider2D), typeof(Animator)); enemy.transform.position = transform.position; enemy.GetComponent <BoxCollider2D>().size = new Vector2(1, 1); enemy.GetComponent <SpriteRenderer>().sprite = currentUnit.artwork; UnitControls enemyScript = enemy.GetComponent <UnitControls>(); enemyScript.unitData = currentUnit; enemyScript.isEnemy = true; gold -= currentUnit.cost; } } } }