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
1
Question by gauge2727 · Dec 08, 2013 at 09:03 PM · arrayaitargeting

C# Targetting Help

Alright, so firstly I'll apologize if I'm not doing this right, but I'm new here...

I'm working on a targetting script for a learning project and have hit a bit of a roadblock I hoped someone with a bit of experience could help me sort. Basically I'm trying to add in functionality of selecting a new target when the specified key is pressed but there are a couple of conditions.

  1. If there is a new target closer than the old target it takes priority.

  2. If there are several targets should cycle through the list of targets with each keypress.

I have the basic functionality in place (though it may not be the best approach) and it sorts by distance and refreshes with the nearest target, I'm just stumped on the rest. I'm open to any suggestions or improvements, but mostly just want a nudge in the right direction. The code is below:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Targetting : MonoBehaviour {
 
     private Transform myTransform;
 
     public List<Transform> targets;
     public Transform selectedTarget;
     public Transform previousTarget;
 
 
     // Use this for initialization
     void Start () {
     
         myTransform = transform;
 
         selectedTarget = null;
         targets = new List<Transform> ();
 
         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);
     }
 
     // Update is called once per frame
     void Update () {
         
         if (Input.GetKeyDown (KeyCode.Tab))
             TargetEnemy ();    
     }
 
     private void TargetEnemy () {
 
         SortTargetsByDistance ();
 
         if (selectedTarget == null) {
 
             selectedTarget = targets[0];
             SelectTarget ();
         }
 
         else {
 
             previousTarget = selectedTarget;
             DeselectTarget ();
             TargetEnemy ();
         }
     }
 
     private void SortTargetsByDistance () {
         
         targets.Sort (delegate(Transform t1, Transform t2) { 
             return (Vector3.Distance (t1.position, myTransform.position).CompareTo(Vector3.Distance (t2.position, myTransform.position)));
         });
     }
 
     private void SelectTarget () {
 
         selectedTarget.renderer.material.color = Color.red;
     }
 
     private void DeselectTarget () {
 
         previousTarget.renderer.material.color = Color.blue;
         selectedTarget = null;
     }
 }



Thanks in advance for any assistance.

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 Fornoreason1000 · Dec 08, 2013 at 09:36 PM

please use useful tags "help..." isn't exactly specific.

back to the question.

ok you want to select targets via index you can adjust the index using your preferred key presses.

     public int index
   Transform closestTarget;
  public void Update() {
       if (Input.GetKeyDown (KeyCode.Tab))
              index++;
              if(index > targets.Count) {
               index = 0;
     }
              TargetEnemy ();  
         }
 }
 
     private void TargetEnemy () {
      
            SortTargetsByDistance ();
             if(closestTarget != targets[0]) {
                   index = 0;
                    closestTarget = targets[0];
               }
            
            if (selectedTarget == null) {
      
              selectedTarget = targets[index];
              SelectTarget ();
            }
      
            else {
      
              previousTarget = selectedTarget;
              DeselectTarget ();
              TargetEnemy ();
            }
             closestTarget = targets[0]
         }

thus way you will cycle through each target in order of distance. next you want to check if targets[0] has changed, that way we can set index to 0 so that the player has no need to cycling all the way through(thus prioritizing the closest target)

Comment
Add comment · Show 2 · 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 gauge2727 · Dec 08, 2013 at 10:05 PM 0
Share

Apologies on the tag thing, it was on the list of "suggested tags" and I wasn't sure how or what to use. I checked out what you suggested, and a couple things didn't quite work so well and I couldn't figure out why.

--Edit-- It's amazing how a set of missing braces can be all the problem in the world. Thanks much! :)

Is this as clean as this code can be? Any tips if not?

avatar image Fornoreason1000 · Dec 09, 2013 at 03:53 PM 0
Share

Clean as memory wise or format wise?

in the end memory wise is all you really care about, since it affects performance and your applications functionality. you want to avoid all unnecessary calls/calculations.

example: setting the screen resolution each frame is unnecessary since you will never change the resolution that many times so quickly, it also quite slow. ins$$anonymous$$d, adjust it when the user changes it.

since your script basally only runs when you the player presses a key, it it's quite well optimized. most program$$anonymous$$g tutors $$anonymous$$ch good practices when it comes to performance. even small irregularity and bad memory operations can build up and still cripple today PC's no problem.

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

17 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

Related Questions

Cycle Through Array of Enemies 1 Answer

If one point is taken go the other point. Quick fix? 2 Answers

How to determine a "cone of influence" used for targeting an object. 2 Answers

on keypress find closest target, then change its tag? 1 Answer

What would be the best way to setup Target priority 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