Question by
denismeatboy · Jun 27, 2021 at 11:19 PM ·
enemy spawn
Why enemies does not appears every 2 seconds?
Hello, I want to create the appearance of enemies in random places with a 2 seconds period, but unfortunately only the first enemy appears and after, the messahe appears in the inscription : "Trying to Invoke method: Main. SpawnEnemy couldn't be called"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Main : MonoBehaviour {
static public Main S;
[Header("Set in Inspector")]
public GameObject[] prefabEnemies;
public float enemySpawnPerSecond = 0.5f;
public float enemyDefaultPadding = 1.5f;
private BoundCheck bndCheck;
void Awake() {
S = this;
bndCheck = GetComponent<BoundCheck> ();
Invoke ("SpawnEnemy", 1f / enemySpawnPerSecond);
}
public void SpawnEnemy () {
int ndx = Random.Range (0, prefabEnemies.Length);
GameObject go = Instantiate<GameObject> (prefabEnemies [ndx]);
float enemyPadding = enemyDefaultPadding;
if (go.GetComponents<BoundCheck> () != null) {
enemyPadding = Mathf.Abs (go.GetComponent<BoundCheck> ().radius);
}
Vector3 pos = Vector3.zero;
float xMin = -bndCheck.camWidth + enemyPadding;
float xMax = bndCheck.camWidth - enemyPadding;
pos.x = Random.Range (xMin, xMax);
pos.y = bndCheck.camHeight + enemyPadding;
go.transform.position = pos;
Invoke (" SpawnEnemy", 1f / enemySpawnPerSecond);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613035551im_/https://answers.unity.com/themes/thub/images/avi.jpg)