Hello, everybody! Now I'm having a little problem with my scripting. This is my code of my AI.
var target : Transform;
function Awake ()
target = GameObject.FindWithTag ("Player");
//the code above has error. "Cant Convert GameObject to Transform". In my function update, I need to use the transform in order to make my AI rotate and move toward the Player.
var relativePos = target.position - transform.position;
So how can I fix that? Thanks in advance!
Answer by CHPedersen
Sep 22, 2011 at 06:29 AM
You're almost there. :)
Your problem is, as the error points out, that GameObject.FindWithTag returns a GameObject, and you want a transform. Fortunately, GameObjects always have a transform. (Since, understandably enough, it's hard to define an object in your game with less detail than at least a position, scale and rotation).
Therefore, to acquire the player's transform, all you have to do is add ".transform" to that:
target = GameObject.FindWithTag ("Player").transform;
Then you're accessing the transform of the GameObject tagged "Player", and not just trying to save the reference to the GameObject itself.
wow!!! Thank you!!! It works!!! ^^
CHPedersen. Thank you so much for you're help and Henry for asking the question
this just saved a ton of trail and error. Thank you.
Answer by alok.kr.029.hotmail
Mar 11, 2014 at 08:49 AM
target = GameObject.Find("Hero").transform;
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
To help users post good questions and use the site effectively we have posted a user guide. Please check it out.
Answers and Comments
5 People are following this question.
Assign a 'Transform' target to prefab by finding a 'GameObject'
Rotating an object in position
parent.transform creates new game object
have array target person of most priority/stick with top prior
Else Statement Not Working