Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 Ranth · Jul 01, 2015 at 09:55 AM · listlists

Adding gameObject to List of different script

I am creating a spaceship fighter RTS. I have two player fighter ships attacking two enemy capital ships. When a capital ship dies, I need it to inform the player's ship of the death so that the player's ships stop attacking it and move onto the next enemyship in their EnemyList script. The EnemyList script is attached to the parent gameObject of the player's fighter ships, and has two lists. One is called enemyList, which lists all the enemies the fighter has been commanded to attack. The second List is called 'objectsToRemove'. On each frame, when objectsToRemove is not null, the EnemyList script will remove any gameObjects in objectsToRemove from enemyList.

Script 1 which calculates death.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class HealthScript : MonoBehaviour {
 
     public int health;
     public int FighterBullet;
     public int Fighter;
     public bool alive;
     private EnemyList adding;
  
     // Use this for initialization
     void Start () {
         alive = true;
     }
     
     // Update is called once per frame
     void Update () {
         
     }
 
 
     void OnTriggerEnter(Collider other)
     {
         //I KNOW THIS LOOKS HORRIBLY INEFFICENT AND WE SHOULD ONLY CALL THE DEATH CHECK AT END, BUT THE PLAYER UNITS DONT FIRE CONTINUALLY THEN
         if (other.gameObject.name == "FighterBullet(Clone)") 
         {
             health = health - FighterBullet;
             Destroy(other.gameObject);
             if (health <= 0 && alive == true) 
             {
                 InformDeath ();
                 gameObject.SetActive (false);
             
             }
         }
         else if  (other.gameObject.name == "Fighter(Clone)")
         {    health = health - Fighter;
             Destroy(other.gameObject);
             if (health <= 0 && alive == true) 
             {
                 InformDeath ();
                 gameObject.SetActive (false);
             }
         }
 
         //Debug.Log ("Enemy health is" + health);
 
 
     }
 
     //this function tells every player unit that it has died. This lets each player unit remove this object from its enemies list;
     void InformDeath()
     {    
         GameObject[] obj = GameObject.FindGameObjectsWithTag("Player");
 
         foreach (GameObject o in obj)
         {
             adding = o.GetComponent<EnemyList>();
             List<GameObject> died = adding.objectsToRemove; // LINE WITH ERROR
             died.Add(gameObject);
 
 
         }
 
         alive = false;
 
         //Destroy the ship after 5 seconds, giving plenty of time for the playerunits to remove it from their arrays
         Destroy(gameObject,5f);
 
     }
 
 }

Script 2 that maintains the enemyList.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class EnemyList : MonoBehaviour {
 
 
     //The purpose of this script is to hold the units current enemy list.
     //This list used to be in the Attack.cs, but when the player goes into 3rd or 1st person mode we turn off Attack
     //At that point, the enemy list is no longer being updated. Therefore, we nee this script to be on constantly to update
     //the list of enemies the player is seeking to kill
 
     public List<GameObject> enemyList  = new List<GameObject>();
     public List<GameObject> objectsToRemove = new List<GameObject>();
     public GameObject currentTarget;
 
     //This bool checks to see if the player selected new enemies to attack. If so, we need to sort and attack
     public bool newList;
     private bool needToSort;
 
     private Attack attackScript;
 
 
 
     // Use this for initialization
     void Start () 
     {
         //Sets list to empty when the unit is instantiated
         enemyList = null;
         attackScript = gameObject.GetComponent<Attack> ();
         objectsToRemove = null;
         needToSort = false;
 
     }
     
     // Update is called once per frame
     void Update () 
     {    
 
         //If the player commands the ship to attack new targets, we need to sort the list and then attack
         if(newList == true) 
         {
             enemyList =   SortList(enemyList);
             attackScript.AttackList(enemyList);
             newList = false;
 
         }
 
         //If we have a list of enemies
         if (enemyList != null) 
         {
             //If we have been told some enemy has died
             if (objectsToRemove != null) 
             {    
                 currentTarget = enemyList[0];
 
                 foreach(GameObject o in objectsToRemove)
                 {
                 //Remove all objects from enemylist, if one of those objects is the current target, need to resort the list
                     if (o == currentTarget) needToSort = true;
                     enemyList.Remove (o);
                 }
 
                 //need to clear this so we dont keep trying to remove the same object
                 objectsToRemove = null;
 
                 if(needToSort == true)
                 {
                 //Sort assuming there are still enemies in the list
                     if(enemyList.Count > 0)
                     {
                         enemyList = SortList (enemyList);
                         attackScript.AttackList (enemyList);
                         needToSort = false;
                     }
                 }
             }
 
             if (enemyList.Count == 0) enemyList = null;
         }
     }
 
     //This sorts the enemy array based on distance to unit;
     public List<GameObject> SortList(List<GameObject> enemyList)
     {
         newList = false;
         //If multiple enemies in list, need to sort the list by distance. Basically compares the distance of the first item in array to next items. If a later item is closer, it becomes first item.
         if (enemyList.Count > 1) 
         {
             for (int e = 1; e <= enemyList.Count-1; e ++) {
                 
                 GameObject enemyinlist1 = (GameObject)enemyList [0];
                 GameObject enemyinlist2 = (GameObject)enemyList [e];
                 
                 float sqrMag1 = (enemyinlist1.transform.position - transform.position).sqrMagnitude;
                 float sqrMag2 = (enemyinlist2.transform.position - transform.position).sqrMagnitude;
                 
                 if (sqrMag2 < sqrMag1) 
                 {
                     GameObject tempStore = (GameObject)enemyList [0];
                     enemyList [0] = enemyList [e];
                     enemyList [e] = tempStore;
                 }
             }
         }
         return enemyList;
     }
 
 
 }
 

In the first script, toward the bottom, I am getting the error " CS1061: NullReferenceException: Object reference not set to an instance of an object." The line is denoted with comments. Therefore, for some reason I am unable to add an item to the objectsToRemove List in the second script.

Note: I was able to get this to work by not having a objectsToRemove as a List, but instead a GameObject, in the second script. However, if two enemies die on the same frame, it would cause issues since it is passing multiple gameOjbects to the script at the same time. Hence, I am trying to use a list.

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

0 Replies

· Add your reply
  • Sort: 

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.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

Respawning gameobject not working c# 0 Answers

Copy values between two classes in two lists. 1 Answer

Make Lists within a List 0 Answers

Help: items not getting added to list. 1 Answer


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