Quantcast
Channel: Questions in topic: "error"
Viewing all articles
Browse latest Browse all 7934

cant kill more than one enemy C#

$
0
0
simpy put using the script below i cant shoot after i kill the first enemy because of an issue at lines 42 and 75, both lines say "EnemyAi enemyAi = enemy.GetComponent();" and the exact error is "The object of type 'EnemyAi' has been destroyed but you are still trying to access it." can anybody help with this? using UnityEngine; using System.Collections; using System.Collections.Generic; public class PistolRay : MonoBehaviour { bool canFire = true; public GameObject decal; public float clipAmmo = 8; public float storedAmmo = 80; float missingShots = 0; GameObject player; GameObject enemy; GameObject characterControler; bool reloading = false; private List enemies = new List(); // Use this for initialization void Start () { player = GameObject.Find("Player"); enemy = GameObject.Find("EnemyAI"); } // Update is called once per frame void Update () { CharacterControler characterControler = player.GetComponent(); characterControler.ammoCount = clipAmmo; characterControler.totalAmmo = storedAmmo; var enemyObjects = GameObject.FindGameObjectsWithTag("Enemy"); foreach(GameObject enemyObj in enemyObjects){ EnemyAi enemyAi = enemyObj.GetComponent(); if(enemyAi != null){ enemies.Add(enemyAi); } } RaycastHit hit; Ray shooterRay = new Ray(transform.position, transform.forward); if(Input.GetButton("Fire1") && canFire && clipAmmo > 0){ StartCoroutine (SoundCooldown(1)); foreach(EnemyAi enemy in enemies){ EnemyAi enemyAi = enemy.GetComponent(); enemyAi.couldHearGun = true; } } if(Input.GetButton("Fire1") && canFire && clipAmmo > 0){ Debug.DrawRay (transform.position, transform.forward, Color.green); if(Physics.Raycast(shooterRay, out hit, Mathf.Infinity)){ if(hit.collider.tag == "Enemy"){ hit.transform.GetComponent().health -= 15; } } var hitRotation = Quaternion.FromToRotation(Vector3.up, hit.normal); Instantiate(decal, hit.point, hitRotation); canFire = false; clipAmmo -= 1; missingShots += 1; StartCoroutine(FireRate(1)); } if(Input.GetButtonDown("Fire1") && canFire && clipAmmo == 0 && !reloading){ reloading = true; StartCoroutine(ReloadTime(3)); } if(Input.GetButtonDown("Reload") && storedAmmo != 8 && !reloading){ reloading = true; StartCoroutine(ReloadTime(3)); } } public IEnumerator FireRate (float delay){ yield return new WaitForSeconds(delay); canFire = true; } public IEnumerator SoundCooldown(float delay){ EnemyAi enemyAi = enemy.GetComponent(); yield return new WaitForSeconds(delay); enemyAi.couldHearGun = false; } public IEnumerator ReloadTime (float delay){ yield return new WaitForSeconds(delay); reloading = false; if(storedAmmo >= 8){ storedAmmo -= missingShots; clipAmmo += missingShots; missingShots = 0; } } }

Viewing all articles
Browse latest Browse all 7934

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>