Question by
amypower94 · Feb 21, 2016 at 09:40 PM ·
targettargetingtargettingenemy health
Targeting Script Errors
To moderators, please don't close this for Null Reference Exception that is not my error. Error is:
Assets/enemyHealth.cs(91,49): error CS0029: Cannot implicitly convert type
UnityEngine.Transform' to
Targetting'
Targetting Script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class Targetting : MonoBehaviour {
public enemyHealth eHealth;
public GameObject enemy;
public List<Transform> targets;
public Transform selectedTarget;
public string targetTag = "Enemy";
private Transform myTransform;
//Use this for initialization
void Start () {
targets = new List<Transform>();
selectedTarget = null;
myTransform = transform;
AddAllEnemies();
}
public void AddAllEnemies() {
GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag);
foreach(GameObject enemy in go) {
AddTarget(enemy.transform);
}
}
public void AddTarget(Transform enemy) {
targets.Add(enemy);
}
private void SortTargetsByDistance() {
targets.RemoveAll(target => target == null);
targets.Sort(delegate(Transform t1, Transform t2) {
return (Vector3.Distance(t1.position, myTransform.position).CompareTo)
(Vector3.Distance(t2.position, myTransform.position));
});
}
private void TargetEnemy() {
if(selectedTarget == null) {
SortTargetsByDistance();
selectedTarget = targets[0];
} else {
int index = targets.IndexOf(selectedTarget);
if (index < targets.Count -1) {
index++;
} else {
index = 0;
}
DeselectTarget();
selectedTarget = targets[index];
}
SelectTarget ();
}
private void SelectTarget() {
selectedTarget.GetComponent<Renderer> ().material.color = Color.red;
enemyHealth eh = (enemyHealth)GetComponent("enemyHealth");
eh.target = selectedTarget.gameObject;
}
private void DeselectTarget() {
selectedTarget.GetComponent<Renderer>().material.color = Color.blue;
selectedTarget = null;
}
//Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.Tab)) {
TargetEnemy ();
}
}
}
and my enemyHealth script:
void Update() {
hitChance = Random.Range (1, 100); // Generates a Random Number each time between 1 and 100
if (Input.GetKeyDown (KeyCode.Alpha1)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 100)) {
if (hit.collider.gameObject.tag == "Enemy") {
selectedTarget = hit.collider.gameObject.transform;
MeleeHit ();
MHCD = Time.time;
}
}
}
Comment