x


Find Transform in the scene

Hello, everybody! Now I'm having a little problem with my scripting. This is my code of my AI.

 var target : Transform;

 function Awake ()
 
 {
 
      if (!target)
      {
 
          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. i.e :

  var relativePos = target.position - transform.position;

So how can I fix that? Thanks in advance!

more ▼

asked Sep 22, 2011 at 06:24 AM

henry96 gravatar image

henry96
657 49 40 47

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Sep 22, 2011 at 06:29 AM

CHPedersen gravatar image

CHPedersen
12.8k 44 64 124

wow!!! Thank you!!! It works!!! ^^

Sep 22, 2011 at 06:47 AM henry96

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.

Aug 13, 2013 at 09:55 AM ownerfate
(comments are locked)
10|3000 characters needed characters left

target = GameObject.Find("Hero").transform;

more ▼

answered Mar 11 at 08:49 AM

alok.kr.029.hotmail gravatar image

alok.kr.029.hotmail
0 4

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x6413
x3706
x2290
x361
x314

asked: Sep 22, 2011 at 06:24 AM

Seen: 5008 times

Last Updated: Mar 11 at 08:49 AM