- Home /
Access SpriteRenderer for random sprite pulled from array (trying to flip sprite if a spawned on a certain side)
I am new to this community and it is getting extremely frustrating seeing all of my questions unanswered and without any comments. I'll continue to try!
I have an enemy spawner that spawns enemies in 1 of 6 spawn points. The spawn points are on the left and right side of the screen. If the enemy is spawned on the right side I want it facing the left side as it runs across. I have done a flip head script where I have used the flipX method, but I am having a difficult time incorporating this into my enemy spawner script mainly due to the script being attached to an empty Gameobject and the spawner using arrays rather than one specific sprite. I am so close and have tried many different approaches, but am stuck. Some help would be appreciated!
Here's my code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TempSpawner : MonoBehaviour{
public float runningPlayerSpeed; //player speed
public Transform []spawnPoints; //for spawn points
public float spawnTime = 2f;
public GameObject [] Players; //array of players(3 total)
public SpriteRenderer mySpriteRenderer;//trying to reference selected Players' sprite render
public float minSpeed;
public float maxSpeed;
private float currentSpeed;
void Awake ()
{
mySpriteRenderer = GetComponent<SpriteRenderer>();
}
void Start(){
InvokeRepeating ("SpawnPlayers", spawnTime, spawnTime);
currentSpeed = Random.Range (minSpeed, maxSpeed);
if (spawnPoints[3]||spawnPoints [4]||spawnPoints [5]) {
mySpriteRenderer.flipX = true;
}
}
void Update(){
float amountToMove = currentSpeed * Time.deltaTime;
transform.Translate (Vector3.right * amountToMove);
int spawnIndex = Random.Range (0, spawnPoints.Length);
int objectIndex = Random.Range (0, Players.Length);
//if enemy spawns on right side of screen - flip the sprite so that it is facing the player
if (spawnPoints [spawnIndex ].position .x==10){
//Players [objectIndex].transform.localScale.x == -1f;
mySpriteRenderer.flipX = true;
//GameObject.FindGameObjectsWithTag ("Running Players");
}
}
//spawn random player in a random spawn location
void SpawnPlayers(){
int spawnIndex = Random.Range (0, spawnPoints.Length);
int objectIndex = Random.Range (0, Players.Length);
Instantiate (Players [objectIndex], spawnPoints [spawnIndex].position, spawnPoints [spawnIndex].rotation );
}
}