My raycast is not activating my enemies death in Unity 3D - c#

I've been trying to make my enemy fall when it's health reaches zero.
So I made a damage variable. The damage will subtract to the health and when it reaches zero or lower, he's supposed to turn into a ragdoll. But its seems as he's not dying in the first place..
In the gun script:
using UnityEngine;
public class gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera Cam;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Fire();
}
void Fire()
{
RaycastHit hit;
if(Physics.Raycast(Cam.transform.position, Cam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Enemy enemy = hit.transform.GetComponent<Enemy>();
if (enemy != null)
{
enemy.damage(damage);
}
}
}
}
}
Now in the enemy script:
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
public class Enemy : MonoBehaviour
{
Animator myAnim;
List<Rigidbody> ragdollRigids;
public float health = 100f;
public void damage (float amount)
{
health -= amount;
if(health <= 0)
{
Death();
}
}
void Death()
{
activateRagdoll();
}
//Update
void Start()
{
myAnim = GetComponent<Animator>();
ragdollRigids = new List<Rigidbody>(transform.GetComponentsInChildren<Rigidbody>());
ragdollRigids.Remove(GetComponent<Rigidbody>());
DeactivateRagdoll();
}
void Update()
{
}
//Ragdoll dependencies.
public void activateRagdoll()
{
myAnim.enabled = false;
for (int i = 0; i < ragdollRigids.Count; i++)
{
ragdollRigids[i].useGravity = true;
ragdollRigids[i].isKinematic = false;
}
}
public void DeactivateRagdoll()
{
myAnim.enabled = true;
for (int i = 0; i < ragdollRigids.Count; i++)
{
ragdollRigids[i].useGravity = false;
ragdollRigids[i].isKinematic = true;
}
}
}
Thank you in advance. :)

Solution
Your variables (damage and amount) are named differently but are used for the same purpose. I have edited your code. There should be no errors. If there are, contact me my commenting on my answer.
Code
Gun:
using UnityEngine;
public class gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera Cam;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Fire();
}
void Fire()
{
RaycastHit hit;
if(Physics.Raycast(Cam.transform.position, Cam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Enemy enemy = hit.transform.GetComponent<Enemy>();
if (enemy != null)
{
enemy.damage(damage);
}
}
}
}
}
Enemy:
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
public class Enemy : MonoBehaviour
{
Animator myAnim;
List<Rigidbody> ragdollRigids;
public float health = 100f;
public void damage (float damage)
{
health -= damage;
if(health <= 0)
{
Death();
}
}
void Death()
{
activateRagdoll();
}
//Update
void Start()
{
myAnim = GetComponent<Animator>();
ragdollRigids = new List<Rigidbody>(transform.GetComponentsInChildren<Rigidbody>());
ragdollRigids.Remove(GetComponent<Rigidbody>());
DeactivateRagdoll();
}
void Update()
{
}
//Ragdoll dependencies.
public void activateRagdoll()
{
myAnim.enabled = false;
for (int i = 0; i < ragdollRigids.Count; i++)
{
ragdollRigids[i].useGravity = true;
ragdollRigids[i].isKinematic = false;
}
}
public void DeactivateRagdoll()
{
myAnim.enabled = true;
for (int i = 0; i < ragdollRigids.Count; i++)
{
ragdollRigids[i].useGravity = false;
ragdollRigids[i].isKinematic = true;
}
}
}

Related

The Spawned enemy only moves, but not shoots in unity

I am new to unity. Recently, I have started making a survival fps game, there, I have 1 enemy, when I kill him, it will spawn more enemies. However, the spawned only move, but not shoot. Although, I have attached a script to it. here are all my code.
prefab_shooting-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class prefab_shooting : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public GameObject player;
public GameObject enemy;
private void Start()
{
player = GameObject.FindWithTag("Player");
enemy = GameObject.FindWithTag("PBR");
}
private void Update()
{
if (Vector3.Distance(transform.position, player.transform.position) < 25.0f)
{
Debug.Log(damage);
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(enemy.transform.position, enemy.transform.forward, out hit, range))
{
if (hit.transform.tag == "Player")
{
swat_death swat = hit.transform.GetComponent<swat_death>();
// Debug.Log(damage);
}
}
}
}
PBR_shooting (the enemy shooting)-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PBR_shooting : MonoBehaviour
{
public float damage = 1f;
public float range = 100f;
public GameObject player;
public GameObject enemy;
private void Start()
{
player = GameObject.FindWithTag("Player");
enemy = GameObject.FindWithTag("PBR");
}
private void Update()
{
if (Vector3.Distance(transform.position, player.transform.position) < 25.0f)
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if(Physics.Raycast(enemy.transform.position, enemy.transform.forward, out hit, range))
{
if(hit.transform.tag == "Player")
{
swat_death swat = hit.transform.GetComponent<swat_death>();
// Debug.Log(swat.health);
swat.TakeDamage(damage);
}
}
}
Swat_death (player_death) -
using UnityEngine;
using UnityEngine.SceneManagement;
public class swat_death : MonoBehaviour
{
static float health = 250f;
public GameObject player;
public void TakeDamage(float amount)
{
health -= amount;
Debug.Log(health);
if (health <= 0f)
{
Debug.Log("STOP");
SceneManager.LoadScene("death_scene");
}
}
void Die()
{
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.tag == "enemy_bullet")
{
//SceneManager.LoadScene("death_scene");
}
}
}
And the PBR_Death (from where the spawning starts) -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PBR_death : MonoBehaviour
{
public GameObject player;
Animator anim;
public int XPos;
public int ZPos;
public GameObject TheEnemy;
public int enemyCount = 0;
public int points = 1;
public GameObject enemyGameObject;
void Start()
{
anim = GetComponent<Animator>();
enemyGameObject = GameObject.FindWithTag("PBR");
}
// Update is called once per frame
void OnCollisionEnter(Collision collision)
{
if (collision.transform.tag == "bullet")
{
anim.SetTrigger("isDying");
enemy_movement enemy = GetComponent<enemy_movement>();
enemy.enabled = false;
PBR_shooting shoot = GetComponent<PBR_shooting>();
shoot.enabled = false;
scoreManager.score += points;
GameObject go = Instantiate(enemyGameObject, new Vector3(Random.Range(34, 0), Random.Range(34, 0), 0), Quaternion.identity) as GameObject;
go.AddComponent<prefab_movement>();
go.AddComponent<prefab_death>();
go.AddComponent<prefab_shooting>();
// StartCoroutine(EnemySpawner());
Destroy(collision.gameObject);
}
}
Pls help me, I am stuck in this for almost 3 days..
You didn't call the function
In your first script (prefab_shooting-) You didn't call the Shoot() function.

How can I remove health from individual instantiated objects in unity?

So my current code removes 5 from the curhealth variable in my enemys once the bullet collides with it. But the issue is, if there is no matter which enemy i shoot and hit, it removes from every single instantiated enemy. I only want to remove health from the enemy who gets hit, how can i fix this?
Enemy.cs
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
using UnityStandardAssets.Characters.FirstPerson;
public interface IDamagable
{
void TakeDamage(int damage);
}
public class Enemy : MonoBehaviour, IDamagable
{
//Health
public float maxHealth = 100f;
static public float curHealth = 100f;
//Health Bar
public Image healthBar;
public Transform goal;
// AI Pathfinding Variables
NavMeshAgent agent;
// Enemy Collision Variables
public float damageCooldown = 1f;
// Start is called before the first frame update
void Start()
{
curHealth = maxHealth;
}
// Update is called once per frame
void Update()
{
// Pathfinding code(?)
agent = GetComponent<NavMeshAgent>();
agent.destination = goal.position;
//Health Bar Image
healthBar.fillAmount = curHealth / maxHealth;
//Death Function
if (curHealth < 1)
{
Destroy(gameObject);
ZombieSpawner.zombieCount--;
}
}
private void OnTriggerEnter(Collider other)
{
curHealth -= Weapon.damage;
}
private void OnCollisionStay(Collision collision)
{
if (damageCooldown > 0f)
{
damageCooldown = damageCooldown - 0.1f;
}
if (collision.rigidbody.name == "Player" && damageCooldown <= 0f)
{
RigidbodyFirstPersonController.playerCurHealth = RigidbodyFirstPersonController.playerCurHealth - 10;
damageCooldown = 1f;
}
}
public void TakeDamage(int damage)
{
curHealth -= damage;
}
private void Awake()
{
//agent = GetComponent<NavMeshAgent>();
}
}
Weapon.cs
using UnityEngine;
using UnityEngine.UI;
public class GunHit
{
public float damage;
public RaycastHit raycastHit;
}
public class Weapon : MonoBehaviour
{
//Weapon Model
public GameObject weaponModel;
public LayerMask mask;
//UI Variables
public Text ammoUI;
// Weapon Variables
static public int damage = 5;
public int ammo = 12;
public int MaxAmmo = 12;
public int reserveAmmo = 90;
public AudioSource fire;
public AudioSource empty;
public bool isAiming = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ammoUI.text = ammo + "/" + reserveAmmo;
weaponFiring();
weaponReload();
}
void weaponAiming()
{
if (Input.GetKeyDown(KeyCode.Mouse1))
{
//weaponModel.transform.position = 0, 0, 0;
}
}
// Default Position = x0, y0, z0.5
public GameObject projectilePrefab;
public GameObject gunBarrel;
void weaponFiring()
{
if (Input.GetKeyDown(KeyCode.Mouse0) && ammo > 0)
{
fire.Play();
Instantiate(projectilePrefab, gunBarrel.transform.position, gunBarrel.transform.rotation);
ammo--;
}
if (Input.GetKeyDown(KeyCode.Mouse0) && ammo == 0)
{
empty.Play();
}
}
void weaponReload()
{
if (Input.GetKeyDown(KeyCode.R))
{
if (ammo == 0)
{
if (reserveAmmo >= MaxAmmo)
{
ammo = MaxAmmo;
reserveAmmo = reserveAmmo - ammo;
}
else
{
ammo = reserveAmmo;
reserveAmmo = 0;
}
}
else if (ammo < MaxAmmo)
{
//Tiddies code
reserveAmmo += ammo;
ammo = 0;
reserveAmmo -= ammo = (reserveAmmo < MaxAmmo ? (reserveAmmo) : (MaxAmmo));
/*
* My code
* ammo = MaxAmmo - ammo;
reserveAmmo = reserveAmmo - ammo;
if (reserveAmmo > MaxAmmo)
{
ammo = MaxAmmo;
}
else if (reserveAmmo < MaxAmmo)
{
ammo = reserveAmmo;
reserveAmmo = 0;
}*/
}
}
}
}
The issue is that your current health variable is static, that means that each enemy is using the same variable for health.
Static makes the varaible global to everybody.
remove the static modifier and the variable becomes personal to each enemy ;)

Unity 2d game Player and enemy not moving

I have been following a tutorial on a unity 2d game. The player and the enemy inherit from a base class known as MovingObject. Everything in the game works fine except that the player and the enemy can't move. Here are the scripts. The movement happens in a gridlike tile system.
This is the original tutorial series. Try going over the moving object, player, and enemy tutorials.
https://www.youtube.com/playlist?list=PLX2vGYjWbI0SKsNH5Rkpxvxr1dPE0Lw8F
Base MovingObject class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class MovingObject : MonoBehaviour {
public float moveTime = 0.1f;
public LayerMask blockinglayer;
private BoxCollider2D boxCollider;
private Rigidbody2D rb2D;
private float inverseMoveTime;
// Use this for initialization
protected virtual void Start () {
boxCollider = GetComponent<BoxCollider2D>();
rb2D = GetComponent<Rigidbody2D>();
inverseMoveTime = 1f / moveTime;
}
protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
{
Vector2 start = transform.position;
Vector2 end = start + new Vector2(xDir, yDir);
boxCollider.enabled = false;
hit = Physics2D.Linecast(start, end, blockinglayer);
boxCollider.enabled = true;
if (hit.transform == null)
{
StartCoroutine(SmoothMovement(end));
return true;
}
return false;
}
protected IEnumerator SmoothMovement(Vector3 end)
{
float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
while (sqrRemainingDistance > float.Epsilon)
{
Vector3 newPosition = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
rb2D.MovePosition(newPosition);
sqrRemainingDistance = (transform.position - end).sqrMagnitude;
yield return null;
}
}
protected virtual void AttemptMove<T>(int xDir, int yDir)
where T : Component
{
RaycastHit2D hit;
bool canMove= Move(xDir, yDir, out hit);
if (hit.transform == null)
{
return;
}
T hitComponent = hit.transform.GetComponent<T>();
if(!canMove && hitComponent != null)
{
OnCantMove(hitComponent);
}
}
protected abstract void OnCantMove<T>(T component)
where T : Component;
// Update is called once per frame
}
Player Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MovingObject {
public int wallDamage = 1;
public int pointsPerFood = 10;
public int pointsPerSoda = 20;
public float restartLevelDelay = 1f;
private Animator animator;
private int food;
// Use this for initialization
protected override void Start () {
animator = GetComponent<Animator>();
food = GameManager.instance.playerFoodPoints;
base.Start();
}
private void OnDisable()
{
GameManager.instance.playerFoodPoints = food;
}
// Update is called once per frame
void Update () {
if (GameManager.instance.playersTurn)
{
return;
}
int horizontal = 0;
int vertical = 0;
horizontal = (int)Input.GetAxisRaw("Horizontal");
vertical = (int)Input.GetAxisRaw("Vertical");
if (horizontal != 0)
{
vertical = 0;
}
if(horizontal!=0 || vertical != 0)
{
AttemptMove<Wall>(horizontal, vertical);
}
}
protected override void OnCantMove<T>(T component)
{
Wall hitwall = component as Wall;
hitwall.damageWall(wallDamage);
animator.SetTrigger("playerChop");
}
protected override void AttemptMove<T>(int xDir, int yDir)
{
food--;
base.AttemptMove<T>(xDir, yDir);
RaycastHit2D hit;
CheckIfGameOver();
GameManager.instance.playersTurn = false;
}
public void LoseFood(int loss)
{
animator.SetTrigger("playerHit");
food -= loss;
CheckIfGameOver();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Exit")
{
Invoke("Restart", restartLevelDelay);
enabled = false;
}
else if (other.tag == "Food")
{
food += pointsPerFood;
other.gameObject.SetActive(false);
}
else if (other.tag == "Soda")
{
food += pointsPerSoda;
other.gameObject.SetActive(false);
}
}
private void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
private void CheckIfGameOver()
{
if (food <= 0)
{
GameManager.instance.GameOver();
}
}
}
Enemy Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MovingObject {
public int playerDamage;
private Animator animator;
private Transform target;
private bool skipmove;
// Use this for initialization
protected override void Start () {
GameManager.instance.AddEnemyToList(this);
animator = GetComponent<Animator>();
target = GameObject.FindGameObjectWithTag("Player").transform;
base.Start();
}
protected override void AttemptMove<T>(int xDir, int yDir)
{
if (skipmove)
{
skipmove = false;
return;
}
base.AttemptMove<T>(xDir, yDir);
}
public void MoveEnemy()
{
int xDir = 0;
int yDir = 0;
if (Mathf.Abs(target.position.x - transform.position.x) < float.Epsilon)
{
yDir = target.position.y > transform.position.y ? 1 : -1;
}
else
{
xDir = target.position.x > transform.position.x ? 1 : -1;
AttemptMove<Player>(xDir,yDir);
}
}
protected override void OnCantMove<T>(T component)
{
Player hitplayer = component as Player;
animator.SetTrigger("enemyAttack");
hitplayer.LoseFood(playerDamage);
}
}
I'm not sure which whether the player or enemy have an issue of the base script. Can anyone help.
A few Observations (Hopefully it helps):
MovingObject.cs - Inside of Update(), should it not be this?
if (!GameManager.instance.playersTurn)
Note I added a "!" before GameManager
Player.cs - in AttemptMove(), you need to call Move()... like this
Move (xDir, yDir, out hit);
Enemy.cs
1) At the end of AttemptMove(), there should be:
skipMove = true;
2) In MoveEnemy(), at the end, this code should NOT be in the else, but after the else:
AttemptMove<Player>(xDir,yDir);

Particle System not working on multiple enemies

I have a particle system for when the enemy is destroyed. I have multiple enemies coming from the same path (using the same prefab) and the particle system is only working on the first enemy. Can someone tell me why it is not working on the others as well? Thank you.
EnemyShooting scrip (this is where the piece of code is for the explosion):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShooting : MonoBehaviour {
[SerializeField] float EnemyLaserSpeed = 10f;
[SerializeField] float EnemyLaserFireTime;
[SerializeField] GameObject LaserBulletEnemyPreFab;
[SerializeField] int MaxNumberOfHits = 1;
public Transform explosion;
int CurrentNumberOfHits = 0;
Coroutine FireCoroutine;
void OnTriggerEnter2D(Collider2D collider)
{
if(collider.gameObject.tag == "PlayerLaser")
{
if (CurrentNumberOfHits < MaxNumberOfHits)
{
CurrentNumberOfHits++;
Destroy(collider.gameObject);
Score.ScoreValue += 2;//The user will be rewarded 1 point
}
if (explosion)//EXPLOSION CODE
{
GameObject exploder = ((Transform)Instantiate(explosion, this.transform.position, this.transform.rotation)).gameObject;
Destroy(exploder, 2.0f);
}
}
}
void DestroyEnemy()
{
if(CurrentNumberOfHits >= MaxNumberOfHits)
{
Destroy(gameObject);
EnemySpawner.Instance.OnEnemyDeath(); // Tell the EnemySpawner that someone died
}
}
private void Fire()
{
FireCoroutine = StartCoroutine(ShootContinuously());
}
void BecomeVisible()
{
Fire();
}
IEnumerator ShootContinuously()
{
while (true)
{
GameObject LaserBulletEnemy = Instantiate(LaserBulletEnemyPreFab, this.transform.position, Quaternion.identity) as GameObject;
LaserBulletEnemy.GetComponent<Rigidbody2D>().velocity = new Vector2(0, EnemyLaserSpeed);
EnemyLaserFireTime = Random.Range(0.5f, 0.9f);
yield return new WaitForSeconds(EnemyLaserFireTime);
}
}
// Use this for initialization
void Start () {
BecomeVisible();
}
// Update is called once per frame
void Update () {
DestroyEnemy();
}
}
EnemySpawner : (I thought this script might help in a way so I attached it)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] GameObject EnemyPreFab;
[SerializeField] int MaxEnemies = 30;
[SerializeField] float EnemySpawnTime = 1.00001f;
[SerializeField] GameObject FirstWaypoint;
int CurrentNumOfEnemies = 0;
public int EnemiesToNextLevel = 7;
public int KilledEnemies = 0;
public LevelManager myLevelManager;
public static EnemySpawner Instance = null;
int timesEnemyHit;
IEnumerator SpawningEnemies()
{
while (CurrentNumOfEnemies <= MaxEnemies)
{
GameObject Enemy = Instantiate(EnemyPreFab, this.transform.position, Quaternion.identity);
CurrentNumOfEnemies++;
yield return new WaitForSeconds(EnemySpawnTime);
}
}
void Start()
{
if (Instance == null)
Instance = this;
StartCoroutine(SpawningEnemies());
timesEnemyHit = 0;
if (this.gameObject.tag == "EnemyHit")
{
CurrentNumOfEnemies++;
}
}
public void OnEnemyDeath()
{
CurrentNumOfEnemies--;
/*
if (CurrentNumOfEnemies < 5)
{
// You killed everyone, change scene:
LaserLevelManager.LoadLevel("NextLevelMenu");
}
*/
KilledEnemies++;
if (KilledEnemies >= EnemiesToNextLevel)
{
LaserLevelManager.LoadLevel("NextLevelMenu");
}
}
}

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

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. :(
In beginning of Update method of your Attack Script, add a null check for target object like this:
if(target == null)
{
return;
}
I think I know what your Timer problems are.
If I have understood correctly, in the Basic Attack class - Start Method, you iniate the timer.
Then, the timer goes down until its 0, and then you can attack.
I think the problem its that, once you have destroyed your enemy, nothing else happens.
I mean, you actually don´t reset the timer once the enemy is dead. That´s why it only works again, when you select another enemy.
When that happens, the BasicAttack class is called from the Targeting class, and thus, the Start method is called again.
I hope it helped.
Regards!

Categories