I have three prefabs which I instantiate with a spawning script. This is the code for it:
public class SpawnManager : MonoBehaviour
{
public GameObject[] enemyPrefabs;
private float spawnRangeX = 7f;
private float spawnPosZ = 26f;
private float startDelay = 2f;
private float spawnInterval = 2f;
public GameObject objToDestroy;
void Start()
{
InvokeRepeating("SpawnRandomEnemy", startDelay, spawnInterval);
}
// Update is called once per frame
void Update()
{
}
void SpawnRandomEnemy()
{
// Make a random enemy from the enemyPrefab to spawn on the fixed X and Y
Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 1, spawnPosZ);
// Initialize enemyIndex to get random enemy from the enemyPrefab in enemyPrefab arrey
int enemyIndex = Random.Range(0, enemyPrefabs.Length);
//Instantiate enemyPrefab of enemyPrefab array at random x and z position and rotate it towards
// the player
Instantiate(enemyPrefabs[enemyIndex], spawnPos, enemyPrefabs[enemyIndex].transform.rotation);
}
I shoot my prefab weapon with:
GameObject prefab;
void Start()
{
prefab = Resources.Load("projectile") as GameObject;
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
GameObject projectile = Instantiate(prefab) as GameObject;
projectile.transform.position = transform.position + Camera.main.transform.forward * 2;
Rigidbody rb = projectile.GetComponent();
rb.velocity = Camera.main.transform.forward * 40;
}
}
}
I have added box colliders to my prefabs and a rigidbody to my weapon. Does someone know how to destroy the enemy prefabs when spawned , when my weapon hits their collider?
↧