• 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 /
avatar image
0
Question by Voridian · Jul 22, 2014 at 12:33 PM · c#errorraycast

cant kill more than one enemy C#

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<EnemyAi> enemies = new List<EnemyAi>();
 
     // 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>();
         characterControler.ammoCount = clipAmmo;
         characterControler.totalAmmo = storedAmmo;
         var enemyObjects = GameObject.FindGameObjectsWithTag("Enemy");
         foreach(GameObject enemyObj in enemyObjects){
         EnemyAi enemyAi = enemyObj.GetComponent<EnemyAi>();
         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>();
             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<EnemyCC>().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<EnemyAi>();
         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;
         }
     }
 }
 

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

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by theLittleSettler · Jul 22, 2014 at 12:59 PM

Ok, you have a variable enemy of type GameObject as well as another variable enemy of type EnemyAi in the foreach loop. That's fine in c#, but it won't help monodevelop's intellisence.

 foreach(EnemyAi enemy in enemies) {

     // this line makes no sense because enemy is type EnemyAi
     // though this.enemy is type GameObject, so it compiles
     EnemyAi enemyAi = enemy.GetComponent<EnemyAi>();

     enemyAi.couldHearGun = true;
 }

You meant...

 foreach(EnemyAi enemyAi in enemies) {
         
     enemyAi.couldHearGun = true;
 }

Keep an eye out for naming conflicts as they tend to cause more confusing bugs.

Comment
Add comment · Show 1 · 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 Voridian · Jul 22, 2014 at 02:27 PM 0
Share

thanks so much, both of you but this is what worked for me

avatar image
0

Answer by Paprik · Jul 22, 2014 at 12:42 PM

You probably didn't remove the enemy object from your list, so you keep cycling through it:

 foreach(GameObject enemyObj in enemyObjects)

When destroying the enemy, you should remove it from enemyObjects as well. Perhaps in the OnDestroy method or wherever you kill it.

Comment
Add comment · Show 1 · 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 Voridian · Jul 22, 2014 at 01:02 PM 0
Share

right, that would make sense. silly question but how do i remove it? i really dont get how lists work tbh. i just added this to the enemies script but it dosnt work:

         if(health <= 0){
             PistolRay pistolRay = pistol.GetComponent<PistolRay>();
             pistolRay.enemies.Remove(pistolRay.enemyAi);
             Destroy(gameObject);
         }
     }

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Raycast stops when false, even in update() 1 Answer

C# Raycast 2D GameObject follow Mouse 1 Answer

Finding Distance between Angles and Points 2 Answers

C# script error. 0 Answers

Errors, Parsing Errors everywhere :( please help 2 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