I have a collider on both the bullet and the Enemy Object and a rigidbody on the enemy and it still doesn’t work. My bullets just go through the enemy. Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile_Move : MonoBehaviour
{
public float speed;
public float fireRate;
public GameObject ourObject;
public GameObject FirePoint;
// Start is called before the first frame update
void Start()
{
FirePoint = GameObject.Find(“FirePoint”);
this.transform.rotation = FirePoint.transform.rotation;
}
// Update is called once per frame
void Update()
{
if (speed != 0)
{
transform.position += transform.forward * (speed * Time.deltaTime);
} else
{
Debug.Log("NoSpeed");
}
void OnCollisionEnter (Collider col)
{
if (GetComponent<Collider>().gameObject.tag == "Enemy") {
Debug.Log("Testing");
Destroy(gameObject);
Debug.Log("Processing");
speed = 0;
//if (col.gameObject.tag == "Enemy")
//{
// Destroy(gameObject);
// Debug.Log("object that was hit: " + ourObject);
// }
}
}
}
}
With “GetComponent().gameObject.tag” You get the tag of the gameObject this script is attached to. In your case you would get the tag your projectile has. You need to use the lines, that you commented out: col.gameObject.tag
Also you are destroying the gameObject this code is attached to, before it can execute the Code.
I think, everythink after Destroy(gameObject); will not execute.
To test if the event is even triggered you could do something like this:
private void OnCollisionEnter(Collision col) {
Debug.Log("Hit object: " + col.gameObject.name);
}
I tried you’re code and it didn’t work
void Update()
{
if (speed != 0)
{
transform.position += transform.forward * (speed * Time.deltaTime);
} else
{
Debug.Log("NoSpeed");
}
void OnCollisionEnter(Collision col)
{
Debug.Log("Hit object: " + col.gameObject.name);
}
// void OnCollisionEnter (Collider col)
// {
// if (GetComponent<Collider>().gameObject.tag == "Enemy") {
// Debug.Log(“Testing”);
// Destroy(gameObject);
// Debug.Log(“Processing”);
// speed = 0;
//if (col.gameObject.tag == “Enemy”)
//{
// Destroy(gameObject);
// Debug.Log("object that was hit: " + ourObject);
// }
}
}
//}
//}
@Jazzhorse
Did you check your bullet’s collider “Is Trigger” true?
If it is true oncollision enter doesn’t work.
Go to your gameobject(bullet). Then go your gameobject collider(Mesh collider or sphere collider etc.)
Check Is Trigger is checked?
and then try @Jazzhorse solution.