- Home /
Help with destroying objects on collision
Hello! I just need some help destroying my player once the enemy bullet hits the player. I have a script to do so, but is doesn't work. If you could also tell me how to change the scene once the player is hit, that would be great. Here is my script: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DestroyPlayer: MonoBehaviour {
void OnTriggerEnter(Collider other) {
if(other.gameObject.tag == "AI Bullet")
Destroy(gameObject);
}
}
I Added AI Bullet Tag to the AI bullet, and I applied this script to the player. I have this same script on the enemy, but it is called DestroyEnemy, and is specific to the enemy. The other script works just fine. Thanks!
Answer by lonelycamper · Jul 07, 2017 at 11:10 PM
Unity is really bad at detecting if something very fast (like a bullet) goes thru a trigger as well instead you should use a raycast Its way better in the long run in your update method you should add this
//Make sure you put a variable public Camera FPSCamera;
//So the ray point knows where to shoot out from at FPSCamera.ScreenPointToRay
Ray ray = FPSCamera.ScreenPointToRay(new Vector2(Screen.width / 2, Screen.height / 2));
RaycastHit hitInfo;
ray.direction = (ray.direction * 100 + UnityEngine.Random.insideUnitSphere * shotRnd).normalized;
Debug.DrawRay(ray.origin, ray.direction * weaponRange, Color.green);
//This checks if right click has been pressed
//If you dont need it so a ray shoots out when right click then just set it to something else
if (Input.GetButton("Fire1") {
if (Physics.Raycast(ray, out hitInfo,)) {
//detects if the gameobject and or collider named Player has been hit
if (hitInfo.collider.tag == "Player"){
//Do something such as //Destroy(hitInfo.transform.gameObject);
//This is getting info from what it hit and then finding the gameObject to destroy
}
}
}
if you don't want to use the ray method you shouldn't use on trigger enter you should probably use void OnCollisionEnter(Collision collision) {} Also when using you should put in the object that its actually hitting by saying Destroy(other.transfrom.gameObject);