I have a player object, and a “Shooter” object that creates instances of a bullet, and that bullet moves toward the player once it is instantiated. The bullet’s update method tracks the player’s position and then moves the bullet toward the direction of the player.
I wanted to use OnCollisionEnter so that when the bullet hits the player it gets destroyed,
The problem is that the actual collision works, but it does not trigger the OnCollisionEnter in the script that is on each instance of the bullet object.
To fix this I tried using OnTriggerEnter instead and setting only the bullet instance to be a trigger, however, this got rid of any collision between the bullet instance and the player object.
To be sure the problem wasn’t because of the player object I put a sphere that had a rigidbody in front of the path that the bullets flew in, and the bullets bounced off the sphere but then continued towards the player, without triggering OnCollisionEnter.
Am I using the OnCollisionEnter method wrong because during any collision the bullet had I didn’t see the debug.log I put in it.
Both the bullet instance and anything it was hitting had a Rigidbody.
Code for the Shooter object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
public GameObject addBullet;
private GameObject player;
private float lastTimeShooted = 0;
private int shoot;
// Start is called before the first frame update
void Start()
{
this.player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
shoot = Random.Range(3, 15);
if((lastTimeShooted + shoot) < Time.time) {
GameObject newInstance = Instantiate(addBullet) as GameObject;
newInstance.transform.position = this.transform.position;
// Bullet bullet = newInstance.GetComponent<Bullet>();
// newInstance.Target = this.player;
lastTimeShooted = Time.time;
}
}
}
Code for the bullet script on each bullet instance:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private float Speed = 3.5f;
public GameObject Target = null;
// Start is called before the first frame update
void Start()
{
Target = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
if (Target != null) {
Debug.Log("Shooting");
float step = Random.Range(1,5) * Time.deltaTime;
this.transform.position = Vector3.MoveTowards(this.transform.position, Target.transform.position + new Vector3(0,0.5f,0), step);
}
}
void OnCollisionEnter(Collision collision)
{
Debug.Log("Collision Works");
GameObject.Destroy(this.gameObject);
}
}
Any help would be greatly appreciated!