- Home /
Targetting Script Error Help
Hi Guys/Girls :) I need help with this Error: Assets/Scripts/Targetting.cs(77,11): error CS0029: Cannot implicitly convert type UnityEngine.GameObject' to
UnityEngine.Transform'
Script:
using UnityEngine;
using System.Collections; using System.Collections.Generic;
public class Targetting : MonoBehaviour { public List targets; public Transform selectedTarget;
private Transform myTransform;
void Start () {
targets = new List<Transform>();
selectedTarget = null;
myTransform = 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);
}
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 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.renderer.material.color = Color.red;
PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack");
pa.target = selectedTarget.gameObject;
}
private void DeselectTarget() {
selectedTarget.renderer.material.color = Color.white;
selectedTarget = null;
}
// Update is called once per frame
void Update () { if(Input.GetButtonDown("Fire1")) { 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; } } } } }
Any Ideas :)?
Answer by Kleptomaniac · Apr 21, 2012 at 04:03 PM
Yeah, that's because selectedTarget is typecast as a Transform, while my code specifies it as a GameObject. My bad. :D Change this line:
selectedTarget = hit.collider.gameObject;
to:
selectedTarget = hit.collider.gameObject.transform;
That should work.
Hope that helped, Klep
I am still having an identical problem, however I don't have a playerattack script. All my scripting for that is in my EnemyHealth. Currently my enemyhealth is not picking up the target from my Targetting script and this line:
I currently get this error:
Assets/Targetting.cs(64,20): error CS0029: Cannot implicitly convert type UnityEngine.Transform' to
UnityEngine.GameObject'