I'm instantiating enemy prefabs in waves, but when I do, the sprites are not consistent on the Z axis. Sometimes the second enemy is on top of the first one, and sometimes behind.
I want the new instance always behind the other.
CodePudding user response:
Keep the instance position and instantiate the gameobject behind.
GameObject myGo1 = GameObject.Instantiate(prefabRef, Vector3.Zero,
Quaternion.Identity);
float distance = 1.0f;
Vector3 myGo2Pos = myGo1.position - myGo1.transform.forward * distance;
GameObject myGo2 = GameObject.Instantiate(prefabRef, myGo2Pos, Quaternion.Identity);
For the 1st GO instatiation, where Vector3.Zero
you can choose the position of your choice. For whatever pos and rot you instantiate myGo1
with, the code Vector3 myGo2Pos = myGo1.position - myGo1.forward * distance;
should instantiate the 2nd one distance
meters behind.
Not debugged code, just for your inspiration.
Probably you might need the 2nd GO to look to the first one, in that case you can do:
GameObject myGo2 = GameObject.Instantiate(prefabRef, myGo2Pos, myGo1.transform.rotation);
CodePudding user response:
Alright i figured it out. had to add a sprite renderer component like so: SpriteRenderer spriteRenderer;
and where i instantiate:
void FollowPath()
{
if (!isAttacking)
{
if (waypointIndex < waypoints.Count)
{
**spriteRenderer = GetComponent<SpriteRenderer>();
spriteRenderer.sortingOrder ;**
Vector3 targetPosition = waypoints[waypointIndex].position;
float delta = waveconfig.GetMoveSpeed() * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);
if (transform.position == targetPosition)
{
waypointIndex ;
}
}
}
}