- Home /
How can I get a GameObject's transform in game and set that to a variable?
I am trying to make a simple game where a cube follows you and you kill it. I want to instantiate the cubes, but my problem is setting the transform that the cube goes for After instantiating the enemy. When I don't instantiate and I just click play, it works (because the transform I use here is the GameObject of the first person controller, not the PREFAB). So my big question is, how can I get the transform of my first person controller and set that to the enemy's target? here's my enemy script:
#pragma strict
var target : Transform;
var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform;
function Awake(){
myTransform = transform;
}
function Start(){
target = GameObject.FindWithTag("First Person Controller").transform;
Debug.Log (target);
}
function Update () {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
Thanks for anyone who can help answer my question. If you need any more information I can provide it. PS I'm not good with Java OR C# but I prefer C#. I didn't do this code above, but everything else was all mine. Thanks for help.
Answer by nesis · Jan 27, 2014 at 01:16 AM
GameObject.Find() could be used to search through all GameObjects to find the one you want. It's recommended to save it to a variable to avoid doing expensive searches too often.
Yes but I'm instantiating a group of them, so they are all "enemy (clone)". I'm not sure one of us understands eachother
Your answer
Follow this Question
Related Questions
How to Return Enemy to startPosition 1 Answer
GetComponent for a stored transform. 0 Answers
Instantiating road pieces without any spacings between 2 Answers
How to spawn object but with child as center of position 0 Answers
transporting player to gameobject when it collides with different gameobject 0 Answers