Hi, I’m a student and quite new with coding in C#.
I’ve tried many times to make a script for my RTS in which spawned prefab units all called “Konijn” (rabbit in Dutch) in the team you play can transform.find all the already existing enemies in the scene with the tag “beer” (bear in Dutch).
The script I used didn’t help at all. A unit could only attack one bear at a time until the bear dies. So I searched for a different script that could work but don’t know how to combine it with the script I already have. Can someone help this newbie out a bit?
SCRIPT THAT DIDN’T WORK CORRECTLY:
using System.Collections;
public class BunnyAttack : MonoBehaviour {
// Set player GameObject as the target in the inspector
public GameObject tag;
// Holds the enemy object's active attack delay timer
public float attackDelay;
// Holds the enemy object's attack cooldown
public float coolDown;
// Holds the enemy object's attack range
public float attackRange;
// Holds how much damage the enemy object does per atk
private int attackPower;
void Start () {
if (tag == null)
tag = GameObject.FindGameObjectsWithTag("beer")[0];
attackDelay = 0;
coolDown = 2.0f;
attackRange = 3.5f;
// Use a negative number for attackPower
// The current health updated logic is
// (currentHealth += attackpower)
attackPower = -10;
}
void Update () {
// Checks if the enemy object can attack.
AttackDelayTimer();
if (tag == null)
tag = GameObject.FindGameObjectsWithTag("beer")[0];
}
private void AttackDelayTimer(){
if (attackDelay > 0){
// If attackDelay is greater then 0,
// Reduce attackDelay by 1 second per cycle
attackDelay -= Time.deltaTime;
}
if (attackDelay < 0){
// Prevents attackDelay from ever becoming less than zero
attackDelay = 0;
}
if (attackDelay == 0) {
// Sets attackDelay to = coolDown to force delay between atk
attackDelay = coolDown;
// Allow an attack
Attack(); // handles object's attacking.
}
}
private void Attack() {
// Calculates the distance between the enemy object and it's target
float distanceFromTarget = Vector3.Distance
(tag.transform.position, transform.position);
if(distanceFromTarget < attackRange) {
// Checks if the target is within attack range
// Loads the target's PlayerHealth script
HealthBarEmpty playerHP = (HealthBarEmpty)
tag.GetComponent("HealthBarEmpty");
// Sends an attack update to the PlayerHealth script
// to reflect the attack
attackPower= -20;
playerHP.AddjustCurrentHealth(attackPower);
}
if(distanceFromTarget > attackRange) {
// Checks if the target is within attack range
// Loads the target's PlayerHealth script
HealthBarEmpty playerHP = (HealthBarEmpty)
tag.GetComponent("HealthBarEmpty");
// Sends an attack update to the PlayerHealth script
// to reflect the attack
attackPower = 0;
}
}
}
THE CODE THAT COULD HELP ME OUT AND I DON’T KNOW WHERE TO PLACE IN THE SCRIPT ABOVE:
foreach(GameObject beerObj in GameObject.FindGameObjectsWithTag("beer"))
{
if(beerObj.name == "beer")
{
//Do Something
}
}