I am making an FPS game. It has pickup-ables (juices/energy) which increases the player's health. Now I'm able to do that with a single cube (just using a cube for testing). The OnTriggerEnter works like a charm, it increases the players health as well as maintains the health bar. But, when I instantiate it, the spawned cubes' triggers don't work.
I've added my "Spawner" and "HealthIncrease" scripts below. Oh yeah, and I have added rigid bodies/box colliders everything.
This is my Spawner Script(I add this to the Empty Game Object)
public class Spawner: MonoBehaviour {
public GameObject Power;
public GameObject player;
public float spawnOffset=3.0f;
public float spawnDelay = 5;
int currentPowerUpCount;
int currentWaveNumber =1;
Vector3 randomSpawnPoint{
get{
int randIndex = UnityEngine.Random.Range(0, transform.childCount-1);
var position = transform.GetChild(randIndex).position + UnityEngine.Random.insideUnitSphere * spawnOffset;
position.y =0;
return position;
}
}
void Start(){
currentPowerUpCount = currentWaveNumber * 3;
Spawn ();
}
void Update(){
CheckifReadySpawn ();
}
void Spawn ()
{
Debug.Log ("spawm" + currentWaveNumber);
for (int i = 0; i < 10; i++) {
var enemyGameobject = (GameObject)Instantiate (Power, randomSpawnPoint, Quaternion.identity);
}
}
void CheckifReadySpawn ()
{
if (currentPowerUpCount <= 0) {
currentWaveNumber++;
currentPowerUpCount = currentWaveNumber * 5;
Invoke ("Spawn", spawnDelay);
}
}
}
This is the HealthIncrease (I add this to the cube)
public class HealthIncrease : MonoBehaviour {
public UISlider healthBar;
public GameObject player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnTriggerEnter (Collider collider) {
if (collider.CompareTag("Player"))
PickItUp ();
}
void PickItUp ()
{
var playerStats = (Stats)player.GetComponent<Stats> ();
if (playerStats.health >= 500) {
return;
}
else {
playerStats.health += 50;
Destroy (this.gameObject);
healthBar.value = playerStats.health / 500;
}
}
}
I'm guessing the prefab for the pickup does not have a collider on it. Note: for collision to work at least one of the objects needs to have a rigidbody and both need to have colliders.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.