- Home /
Enemy attack when it spawns
Hello! Sorry if this is a dumb question but i'm new to unity. Right now i have a script that makes the enemies spawn in four positions with a delay, but now i need the enemy to attack the player a couple seconds after it spawns. I'm having trouble doing that, but also when the enemy attacks an image should appear on the screen to make the player realize it has been attack, and i don't know how to do that without a bullet or something that collides with the player. Here's my spawn script
public class TimedSpawn : MonoBehaviour {
public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;
// Use this for initialization
void Start () {
InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}
public void SpawnObject (){
Instantiate (spawnee, transform.position, transform.rotation);
if (stopSpawning) {
CancelInvoke ("SpawnObject");
}
}
}
Answer by AidanHorton · Nov 01, 2017 at 11:58 AM
What you should do to attack the player after a certain amount of time is start an 'IEnumerator', which allows you to use 'WaitForSeconds'. Call the 'IEnumerator' function after the enemy has spawned, and pass a reference of the enemy to the function. After a few seconds, call the 'enemy.attack' command (or whatever your attack command is).
public class TimedSpawn : MonoBehaviour {
public GameObject spawnee;
public bool stopSpawning;
public float spawnTime;
public float spawnDelay;
// Use this for initialization
void Start () {
InvokeRepeating ("SpawnObject", spawnTime, spawnDelay);
}
public void SpawnObject (){
GameObject enemy = (GameObject)Instantiate (spawnee, transform.position, transform.rotation);
//Call the IEnumerator function, and pass it 'enemy'
StartCoroutine(Attack(enemy));
if (stopSpawning) {
CancelInvoke ("SpawnObject");
}
}
IEnumerator Attack(GameObject enemy) {
//Wait for 5 seconds
yield return new WaitForSeconds(5.0f);
//Attack here! - Something like 'enemy.GetComponent<enemy_script>().Attack();'
}
}
As for your other issue you should look into UI (to display the image): https://docs.unity3d.com/Manual/UISystem.html, and Rigidbody collisions for when the bullet hits the player: https://docs.unity3d.com/ScriptReference/Rigidbody.OnCollisionEnter.html