Cannot convert 'UnityEngine.GameObject' to 'UnityEngine.Vector3' Why is this?
I'm trying to make a turret that shoots a game object with the tag "targetObject", however I keep on getting the same error and thanks to MonoDevelop's very unclear debugging system, I'm not sure how to fix it. (I am new to Unity) Thanks!
pragma strict
var turretsOn : boolean = true;
private var targetPosition : Vector3;
function Start () {
aimStart();
}
function aimStart() {
//Just a loop :)
while (turretsOn === true) {
//We only want the turret to aim every second, for perfromance and gameplay.
yield WaitForSeconds(1);
targetPosition = GetClosestObject("targetObject");
Transform.LookAt(Vector3(targetPosition));
}
}
function GetClosestObject(tag:String) : GameObject {
var objectsWithTag = GameObject.FindGameObjectsWithTag(tag);
var closestObject : GameObject;
for (var obj : GameObject in objectsWithTag) {
if(!closestObject) {
closestObject = obj;
}
//Compares distances
if(Vector3.Distance(transform.position, obj.transform.position) <= Vector3.Distance(transform.position, closestObject.transform.position)) {
closestObject = obj;
}
}
return closestObject;
Answer by NoseKills · Nov 18, 2015 at 09:08 PM
Just like the error is telling you, your function
function GetClosestObject(tag:String) : GameObject
returns a GameObject and you are trying to assign that gameObject into a Vector3 variable
private var targetPosition : Vector3;
If you are trying to store the position of that gameObject, reference it's position vector and store that
targetPosition = GetClosestObject("targetObject").transform.position;
Edit: I fixed this as it was an error by me using an upper case letter for 'transform'.
Thanks for such a quick answer, however I now get "The type 'UnityEngine.Vector3' does not have a visible constructor that matches the arguement list '(UnityEngine.Vector3)'" This is on line 19.
Your answer
Follow this Question
Related Questions
Get All Game Objects Between 2 Points 1 Answer
Maintaining look at target between two cameras 1 Answer
Need help making my code more efficient 0 Answers
Need help getting randomly moving particles to head to the nearest of 4 coordinates. 1 Answer
(C#/OOP) Accessing one public function belonging to multiple gameObjects? 2 Answers