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 Djspun · Sep 11, 2013 at 04:23 AM · c#selecting objects

Help i need a way to target the enemy with tab key

my attack script i want to press tab and it select the target(Enemy)witch is a Gameobject if you can help finish my code ill be forever grateful:)

/// /// PlayerAttack.cs /// /// This is a basic attack script to get us use to usng C# and Unity /// /// Attach ths script to your player /// using UnityEngine; using System.Collections;

public class PlayerAttack : MonoBehaviour { public GameObject target; public float attackTimer; public float coolDown;

 // Use this for initialization
 void Start () {
     attackTimer = 0;
     coolDown = 2.0f;
 }
 
 // Update is called once per frame
 void Update () {
     if(attackTimer > 0)
         attackTimer -= Time.deltaTime;
     
     if(attackTimer < 0)
         attackTimer = 0;
     
     if(Input.GetKeyUp(KeyCode.Mouse0)) {
         if(attackTimer == 0) {
             Attack();
             attackTimer = coolDown;
             
             
         }
     }
 
 }
 
 private void Attack() {
     float distance = Vector3.Distance(target.transform.position, transform.position);
     
     Vector3 dir = (target.transform.position - transform.position).normalized;
     
     float direction = Vector3.Dot(dir, transform.forward);
     
     if(distance < 2.5f) {
         if(direction > 0) {
             EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
             eh.AddjustCurrentHealth(-10);
         }
     }
 }

}

Comment
Add comment · Show 1
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 meat5000 ♦ · Jun 03, 2014 at 01:33 AM 0
Share

-1 Answers Bug

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Azmodii · Sep 11, 2013 at 06:56 AM

There are two things that would need to happen here. Firstly, you would need to know what targets are on the screen and their relative distance from the player.

You can figure out what objects are visible to a certain camera by checking out this code. You simply include the C# script in your project.

Now we need get a list of GameObjects for this function to iterate through to figure out if they are visible. The easiest way is to tag enemies and then use GameObject.FindGameObjectsWithTag. Also see here for how to setup tags in the tag manager.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;

Make sure to include the above at the TOP of your script, before the class declaration.

 List<GameObject> AllEnemiesList = GameObject.FindGameObjectsWithTag("enemies");
 List<GameObject> VisibleEnemiesList = new List<GameObject>();

This code will then get a list of all GameObjects tagged with this particular tag. Now we can check if these are currently being rendered by the main camera.

 foreach (Transform Enemy in EnemiesList) {
     if (Enemy.GameObject.renderer.IsVisibleFrom(Camera.main)) {
         VisibleEnemiesList.Add (Enemy.GameObject);
     }
 } 

Now we have a list which has all the visible enemies to the main camera!

Secondly, you would need to provide a function that executes when the tab key is pressed. You can do this by placing this code in Update ().

 if (Input.GetKey (KeyCode.Tab)) {
     //Do something here
 }

Now I cant provide you the code here, you will need to decide how to sort the list so the target changes (Perhaps left to right? Perhaps by relative distance to the player IE closer enemies first?), but this will at least send you in the right direction :)

Comment
Add comment · Show 6 · 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 Djspun · Sep 11, 2013 at 01:55 PM 0
Share

thanks alot ive added in the code but i get an error could you help me figure what im doing wrong :P i get this (Assets/_Scripts/random scripts/PlayerAttack.cs(17,54): error CS0029: Cannot implicitly convert type UnityEngine.GameObject[]' to System.Collections.Generic.List')

i know for a fact i want it to select the targets closest to the player and deselect when i select the next

heres the script

/// /// PlayerAttack.cs /// /// This is a basic attack script to get us use to usng C# and Unity /// /// Attach ths script to your player /// using UnityEngine; using System.Collections; using System.Collections.Generic;

public class PlayerAttack : $$anonymous$$onoBehaviour { public GameObject target; public float attackTimer; public float coolDown;

 List<GameObject> AllEnemiesList = GameObject.FindGameObjectsWithTag("Enemy"); 
 List<GameObject> VisibleEnemiesList = new List<GameObject>();


 // Use this for initialization
 void Start () {
     attackTimer = 0;
     coolDown = 2.0f;
     
     foreach (Transform Enemy in EnemiesList) {
 if (Enemy.GameObject.renderer.IsVisibleFrom(Camera.main)) {
     VisibleEnemiesList.Add (Enemy.GameObject);
 }

} }

 // Update is called once per frame
 void Update () {
     if(attackTimer > 0)
         attackTimer -= Time.deltaTime;
     
     if(attackTimer < 0)
         attackTimer = 0;
     
     if(Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.$$anonymous$$ouse0)) {
         if(attackTimer == 0) {
             Attack();
             attackTimer = coolDown;
             
             
         }
         if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.Tab)) {
             TargetEnemy();

} }

 }
 
 private void Attack() {
     float distance = Vector3.Distance(target.transform.position, transform.position);
     
     Vector3 dir = (target.transform.position - transform.position).normalized;
     
     float direction = Vector3.Dot(dir, transform.forward);
     
     if(distance < 2.5f) {
         if(direction > 0) {
             EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
             eh.AddjustCurrentHealth(-10);
         }
     }
 }

}

thanks agian for all the help

avatar image Azmodii · Sep 11, 2013 at 11:52 PM 0
Share

Hi,

Sorry I made a boo boo in my code!

Replace:

 List<GameObject> AllEnemiesList = GameObject.FindGameObjectsWithTag("Enemy");

With:

 GameObject[] AllEnemiesList = GameObject.FindGameObjectsWithTag("Enemy");

And then replace:

     foreach (Transform Enemy in EnemiesList) {
         if (Enemy.GameObject.renderer.IsVisibleFrom(Camera.main)) {
         VisibleEnemiesList.Add (Enemy.GameObject);
 }

With:

 foreach (GameObject Enemy in EnemiesList) {
     if (Enemy.renderer.IsVisibleFrom(Camera.main)) {
     VisibleEnemiesList.Add (Enemy);
 }
avatar image Azmodii · Sep 11, 2013 at 11:57 PM 0
Share

And with regards to selecting the closest enemy, you would need to iterate through this new VisibleEnemiesList and find which enemy was closest.

You would likely need another list that you could store these objects in order of distance, but there may be a better way of doing this.

avatar image Djspun · Sep 12, 2013 at 02:17 AM 0
Share

looks better only erros i have is this and i forgot how to add them to the current context help once agian if possible

Assets/_Scripts/random scripts/PlayerAttack.cs(28,46): error CS0103: The name EnemiesList' does not exist in the current context and this Assets/_Scripts/random scripts/PlayerAttack.cs(51,33): error CS0103: The name TargetEnemy' does not exist in the current context

/// /// PlayerAttack.cs /// /// This is a basic attack script to get us use to usng C# and Unity /// /// Attach ths script to your player /// using UnityEngine; using System.Collections; using System.Collections.Generic;

public class PlayerAttack : $$anonymous$$onoBehaviour { public GameObject target; public float attackTimer; public float coolDown; public int EnimiesList;

 GameObject[] AllEnemiesList = GameObject.FindGameObjectsWithTag("Enemy"); 
 List<GameObject> VisibleEnemiesList = new List<GameObject>();


 // Use this for initialization
 void Start () {
     attackTimer = 0;
     coolDown = 2.0f;
     
     foreach (GameObject Enemy in EnemiesList) {
 if (Enemy.renderer.IsVisibleFrom(Camera.main)) {
 VisibleEnemiesList.Add (Enemy);
 }

} }

 // Update is called once per frame
 void Update () {
     if(attackTimer > 0)
         attackTimer -= Time.deltaTime;
     
     if(attackTimer < 0)
         attackTimer = 0;
     
     if(Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.$$anonymous$$ouse0)) {
         if(attackTimer == 0) {
             Attack();
             attackTimer = coolDown;
             
             
         }
         if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.Tab)) {
             TargetEnemy();

} }

 }
 
 private void Attack() {
     float distance = Vector3.Distance(target.transform.position, transform.position);
     
     Vector3 dir = (target.transform.position - transform.position).normalized;
     
     float direction = Vector3.Dot(dir, transform.forward);
     
     if(distance < 2.5f) {
         if(direction > 0) {
             EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
             eh.AddjustCurrentHealth(-10);
         }
     }
 }

}

thanks agian for all your help would there be another way to contact you for other help if not ill continue to use these forums

avatar image Djspun · Sep 30, 2013 at 03:06 AM 0
Share

i reverted to my old script and finally got it working with some help thanks any ways your method just was not working for me

Show more comments

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

18 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

Related Questions

Distribute terrain in zones 3 Answers

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Multiple Cars not working 1 Answer

Can't use any variable from different class/ NullReferenceExcept 0 Answers

C# Randomly Adding Elements from stringListA to stringListB 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