I’m very new to coding so this is probably a very easy question to answer. I have a sprite who shoots bullets after space is pressed I want them to disappear or be killed after contact with another object in the level. Here is my code for the contact and kill so far:
function OnCollisionEnter(platforms){
Destroy (weapon.bullets);
}
This gives me an error saying that ‘funtion’ is an “unexpected identifier” Please help…
void OnCollisionEnter(Collision Other)
{
Destroy (this.gameobject);
}
Create a new script called Bullet.cs and add it to your bullet prefab. Also ensure that the bullet has a collider.
Note: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached
public class Bullet : MonoBehaviour {
void OnCollisionEnter(Collision other) {
// Collision other => containing information about the other object, this gameobject did hit.
// Check https://docs.unity3d.com/ScriptReference/Collision.html
// Whenever a gameobject with this script enter a valid collision it will destroy itself.
Destroy(gameObject);
}
}
Depending on your game I would say there can be easier ways to do it.
For example if the visual or any physics behaviour like gravity is not needed for the bullet. You could instead use a Raycast in your shooting function like in my example below.
// the distance of the raycast
public float fireLength = 10;
// cooldown between bullets in seconds
public float fireRate = .1f;
bool isShooting;
RaycastHit hit;
void Update() {
var leftClick = Input.GetMouseButtonDown(0);
if (leftClick && !isShooting) {
isShooting = true;
Shoot();
}
}
IEnumerator Shoot() {
// This will create a raycast to the center of our active camera view.
// If you isn't creating a first person shooter, this isn't exactly what you are
// looking for, but you can change this by updating
// the parameters passed to the Ray below.
// Check out https://docs.unity3d.com/ScriptReference/Ray-ctor.html
Ray ray = Camera.main.ViewportPointToRay(new Vector2(.5f, .5f));
if (Physics.Raycast(ray, out hit, fireLength)) {
if(hit.collider.CompareTag("Player")) {
Debug.Log("We hit a player!");
}
}
yield return new WaitForSeconds(fireRate);
isShooting = false;
}
In case you are building a 2D game you should look at Unity - Scripting API: Physics2D.Raycast