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);
}
}
}
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