I can shoot bullets from a gameobject on FPS but how do I detect a hot with an object? I shoot an object called "Wall" with a bullet but no hi gets detected? Code (csharp): void Update () { if (Input.GetKeyDown("c")) { Debug.Log("c key was pressed"); Rigidbody mybullet; mybullet = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody; mybullet.AddForce(transform.forward * 1000); // mybullet.AddForce(transform.up * 400); Destroy(mybullet.gameObject,3); _bullets2.Add(mybullet); ..... void OnCollisionEnter(Collision collision) { if (collision.gameObject.name=="Wall") { Debug.Log("Hit wall2"); } }
I have tried continuous setting, slowing the bullet down but I am not registering any hit at all? The below code never gets triggered even though the bullet bounces off the wall and an enemy as a cube? void OnCollisionEnter(Collision collision) { Debug.Log("Hit "+collision.gameObject.name); }
This also has no effect? I have no idea why no collision cant be detected. void OnTriggerEnter(Collider other) { Debug.Log("ihit=" + other.gameObject.name); }
I could be wrong, but in my code i use.... onCollisionEnter(collision : Collision) Instance, then class.
You are wrong. He's using C#, in which case the syntax is correct. Do a Debug.Log(collision.gameObject.name) to see what is actually being registered. Should help to clear things up.
OnCollisionEnter won't get called because it needs to be in a script that's attached to your bullet, not your gun. But Jessica1986 is right - you shouldn't be spawning individual bullets (as it's very slow), you should be using a raycast to simulate the 'entire path' of the bullet in one go. Just cast a ray from the 'tip' of the gun, in the direction the gun is pointing, and see what you hit.
Is there a bug with this collision event because I am getting nothing and my bullets bounce off the wall slowly. Nothing is being output? Both th wall and bullet have rigidbody and colliders. void OnCollisionEnter(Collision collision){ Debug.Log("Hit "+collision.gameObject.name);
I attached the collision code to the bullet prefab and it all works. Well done for picking this up Why use a raycast then? If I use raycast there are 2 types and which do I use and how do i use it?
There are 4 types, but they all do ultimately the same thing. You'll want to use one of the ones that fills out a RaycastHit structure. You just call it with the ray you want to test, and if it returns true, you hit something - then check in the RaycastHit structure for the exact point hit (for impact effects) and the object that got hit. The examples on the docs page should get you started.