Moving an instantiated gameobject problem
This problem I imagine is easy to fix but I can't seem to figure out how to fix the problem.
Basically I'm spawning a bunch of objects with a for statement around the player and then i want it to move those objects towards the player. I created this function to try and do that:
public IEnumerator CirclePellet()
{
Vector2 playerPosition = player.transform.position;
textManager.DisableTextBox();
for(int i = 0; i < 25; i++)
{
Vector2 pos = CirclePlayer(playerPosition, 3.0f);
Quaternion rot = Quaternion.FromToRotation(Vector2.down, playerPosition-pos);
pellet = Instantiate(PelletCircle, pos, rot) as GameObject;
yield return new WaitForSeconds(0.1f);
}
yield return new WaitForSeconds(1f);
pellet.transform.position = Vector2.MoveTowards(pellet.transform.position, playerPosition, 5 * Time.deltaTime);
}
I've also simply assignment the variables at the top of the script:
public GameObject player;
public GameObject PelletCircle;
public GameObject pellet;
This is also the function I calling to get the position:
Vector2 CirclePlayer(Vector2 centre, float range)
{
float ang = Random.value * 360;
Vector2 pos;
pos.x = centre.x + range * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.y = centre.y + range * Mathf.Cos(ang * Mathf.Deg2Rad);
return pos;
}
So the spawning of the objects works fine and they all spawn around the player but the one thing I can't get them to do is move towards the player and I don't know why. Does anyone know what I'm doing wrong?
Thanks
Answer by maestroxxx · Mar 08, 2016 at 07:31 PM
At the time you move the pellet, it is a reference to" only the last" pellet you created!
public GameObject PelletCircle; <= the code here is also strange with that highlighting;
And how often do you call CirclePellet()? You would have to call in in Update() for the moving but then your code would also create new pellets all the time and reference "a new last one! again.
If I understood you correctly, I would create a "move" script that has the moving code in its update. Instantiate the pellets the way you do it and give each of them the "move" script.
Your answer
![](https://koobas.hobune.stream/wayback/20220612071002im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Javascript Script for Object Follow? 0 Answers
Path Movement created from user input.mouse and player follows it. 0 Answers
How do you get different parts of the same object to move in different ways? 1 Answer
What is the best way to rotate an object with marker points ? 0 Answers
Enemy jump to player position then stop? 0 Answers