Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 CoolCasualCat · Oct 23, 2015 at 12:22 PM · c#transformarraylistdynamic

Dynamic Enemy Transform List

In my game, there are survivors and zombies. Each of the few survivors will need to be able to find all the zombies in the scene and add them to the list. Then each survivor needs to sort the list of transforms by distance. And the zombie closest to the barrier the zombies stand behind will be the selected target. The selected target will be used by all the survivors in the scene, and will be used in a "lookat" function so the survivors that shoot automatically will always face the zombie of greatest threat.

So far, this is what I have:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 [RequireComponent (typeof (NavMeshAgent))]
 public class SurvivorController : MonoBehaviour 
 {
     public PoolingSystem pS = PoolingSystem.Instance;
     public Gun gun;
     //public ZombieController zombieCont;
 
     NavMeshAgent agent;
     public GameObject zombie;
     public List<Transform> targets;
     public Transform selectedTarget;
     private Transform myTransform;
 
     public bool targetsAvailable;
 
     public Transform spawn;
     
     void Start()
     {
         agent = GetComponent<NavMeshAgent> ();
         targets = new List<Transform>();
 
         myTransform = transform;
         InvokeRepeating ("UpdateList", 0f, 1f);
     }
 
     void UpdateList()
     {
         RemoveAllZombies ();
         AddAllZombies ();
     }
 
     void StartShooting()
     {
         //gun.InvokeShoot ();
         print ("start shooting");
     }
 
     void StopShooting()
     {
         gun.CancelInvokeShoot ();
     }
 
     public void RemoveAllZombies()
     {
         targets.Clear ();
     }
 
     public void AddAllZombies()
     {
         GameObject[] go = GameObject.FindGameObjectsWithTag ("Zombie");
         foreach (GameObject zombie in go) 
         {
             AddTarget (zombie.transform);
         }
     }
 
     public void RemoveZombie()
     {
         if (targets.Count > 0) 
         {
             targets.RemoveAt(0);
             print ("Zombie Count:" + targets.Count);
         }
     }
 
     void Update()
     {
         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
         RaycastHit hit;
             if (Input.GetMouseButtonDown (0)) 
             {
                 if(Physics.Raycast(ray, out hit))
                 agent.destination = hit.point;
                 agent.Resume();
             }
         transform.LookAt(selectedTarget);
         TargetZombie();
     }
 
     private void SortTargets()
     {
         targets.Sort (delegate(Transform t1, Transform t2) 
                       {
             return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
         });
     }
 
     private void TargetZombie()
     {
         if (targets.Count <= 0) {
             selectedTarget = null;
             targetsAvailable = false;
             StopShooting();
         } 
 
         if(targets.Count > 0) 
         {
             selectedTarget = targets [0];
             targetsAvailable = true;
             SortTargets();
         }
     }
 
     public void AddTarget(Transform zombie)
     {
         targets.Add (zombie);
     }
 }


Sorry if it's not organized well. But basically the problem, is that when I spawn a new zombie, I don't know how to just add it to the list. At first I tried to call the AddAllZombies method. Then I observed how it added all the zombies that already existed in the scene thus doubling the size of the list.

The only way I am able to update the list, is by clearing the entire list and then call the AddAllZombies method immediately right after. And this only works when I do it pretty fast. Which is why you see a method just for this (UpdateList), in which I InvokeRepeat in the "Start()".

And then this ridiculous UpdateList() method also affects the SortTargets() Method. I just need a way to dynamically add a zombie as a transform to the list that already existed in the scene. Sorry if this was too long or confusing. Please ask me to clarify anything that is unclear and thank you very much for any help!

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

1 Reply

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

Answer by fafase · Oct 23, 2015 at 01:48 PM

Instead of having the list in a survivor object, you should maybe store it on a manager.

Then all survivors are just looking at that list. This way, a new zombie adds itself to only one list and everyone is "aware".

Then you can use :

  Transform FindClosestEnemy() {
     Transform closest = null;
     float distance = Mathf.Infinity;
     Vector3 position = transform.position;
     foreach (Transform tr in list) {
         Vector3 diff = tr.position - position;
         float curDistance = diff.sqrMagnitude;
         if (curDistance < distance) {
             closest = go;
             distance = curDistance;
         }
     }
     return closest;
 }


Your manager would have Add/RemoveZombie(Transform) methods. So when you create a new one:

 ZombieManager manager = null;
 void Start(){
      manager = FindObjectOfType<ZombieManager>();
      if(manager != null){
         manager.AddZombie(this.transform);
      }
 }
 void OnDestroy(){
      if(manager != null){
         manager.RemoveZombie(this.transform);
      }
 }

Comment
Add comment · 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

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

How to check if the string is on a text file 0 Answers

Brute Force Search Algorithm 0 Answers

Give a name for each class in List/array 2 Answers

C# Enemy list for player to attack 2D 1 Answer

how can i check if there is a blanc spot in my list 3 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