- Home /
Other
Instantiate Object Problem
Hi
I'm making a 2d space shooter, very typical controls, WASD to move and mouse to shoot. I began with a set amount of enemies that I placed by hand, but I obviously don't want that, so I'm trying to instantiate them dynamically.
Here's the problem..The enemies are spawned in fine, but their behavior seems to be wrong according to my code. I want them to simply look at the location of the player, then move in that direction. The most stupid AI, but it should work on update.
The enemies that I placed by hand work fine, but only the instantiated clones will not properly work. Instead of tracking the player's position on update, they appear to be only ever moving toward the starting position of the player at the beginning of the game.
In my player class, I instantiate the enemies like:
public void SpawnEnemies() {
int x = 0;
while (x < 10) {
Vector3 ppos = transform.position;
Vector3 spos = new Vector3(0, 0, 0);
spos.Set(ppos.x + x + 5, ppos.y + x, ppos.z);
Instantiate (enemy1, spos, transform.rotation);
numEnemies++;
x++;
}
}
And in the enemy class, where I believe the issue lies, they move like this. Note that the variable player
is a Transform
that is set to the prefab of the player.
void Update () {
transform.LookAt (player);
transform.position += transform.forward * speed * Time.deltaTime;
}
To reiterate, if I place enemy prefabs in the world by hand, they will behave as intended, but an instantiated clone appears to only ever look at the original starting point of the player. I realize that this is the location in the world that I placed the player prefab, however, I can't see any reason that this doesn't work. Additionally, during runtime I checked to make sure that the clones were being cloned with the proper variables and references via the Inspector, and they are.
Any help is greatly appreciated.
Solved it, I had to update the player field in the script of the enemy after it had been instantiated.