- Home /
Solved problem on my own
Using Vector3.MoveTowards with each GameObject in a list
Below is my script for storing targets in a list and instantiating a missile to go to each target in the list. I can clearly print the position of each object in the list, but when I instantiate the missile(s), they do not move. How do I pass the position of each object to the missiles so they go to the targets?
void fireControl(){ //called from Buttons.cs when fire button is down
//Increment frame counter while held
frameCounter = frameCounter + 1;
if (frameCounter >= lockDelay){
myguiText.text = "Lock On";
//change reticle to lock on texture if held for delay period
img.texture = (Texture)Locked;
img2.texture = (Texture)Locked;
//add enemies to array
if (objCount < 4 && target != obj){
TargetList.Add (target as GameObject);
objCount = objCount + 1;
obj = target;
}
}
}
void fireMissiles(){
print ("Fire Missiles");
float step = speed * Time.deltaTime;
//check for number of items in array
foreach (GameObject newtarget in TargetList) {
//get location and send bullet
gameObject.GetComponent<Transform>();
print(newtarget.transform.position);
GameObject fired2 = Instantiate (Missile, playerLocation, Quaternion.identity);
fired2.transform.position = Vector3.MoveTowards (fired2.transform.position, newtarget.transform.position, step);
}
//clear list after button release
TargetList.Clear();
}
}
Answer by Captain_Pineapple · Nov 13, 2019 at 08:25 AM
sigh
please read the documentation on things before you start using them... ->Documentation for MoveTowards
you should give some "homingAction" script to your missle where you implement it's movement. There you should then set the target after instantiation..
Answer by Ermiq · Nov 13, 2019 at 02:12 PM
MoveTowards() must be placed in the Update() loop to work. In your code you have just one iteration of the MoveTowards() that fires only once and it moves the missile for just one step. To continue the movement you have to call MoveTowards() again and again. PS: What is the gameObject.GetComponent<Transform>()
for? You don't need that. Just use gameObject.transform
.
...or just cache transform and use that (if it's in Update)
Well, yes, you're right. If you need to get just this.transform
then it's just transform
. However, if the object is some other object then it will be someObject.transform
.
Follow this Question
Related Questions
Transform List not updating position of prefab. 2 Answers
Adding prefabs to a list or an array from a folder and instantiating them. 2 Answers
Spawn List of game Objects 3 Answers
Checking if object intersects? 1 Answer
Moving instantiated prefab from randomly chosen startPoint to randomly chosen endPoint 1 Answer