I'm trying to get my PlayerHealth script to calculate damage when colliding with a laser shot. I've got the health bar to appear and values seems to apply correctly, but my script isn't detecting the collision nor subtracting health when the collision happens (obviously because it's not detecting the collision). I actually want the lasershot to be a physical thing in the game world, so I don't think using it as a trigger is the best solution. Anyway here is my code: Code (CSharp): using UnityEngine; using System.Collections; public class PlayerHealth : MonoBehaviour { public int maxHealth = 5; public int curHealth = 5; public int laserDamage = 1; void OnGUI() { GUI.Box(new Rect(5, 5, Screen.width / 3 / (maxHealth / curHealth), 20), curHealth + "/" + maxHealth); } void onCollisionEnter (Collision collision) { if (collision.collider.gameObject.tag == "Laser") { Debug.Log ("Hit!"); curHealth = curHealth - laserDamage; } } }
OnCollisionEnter not onCollisionEnter also, OnGUI is the old legacy UI system, have a look at the newer canvas UI system: https://unity3d.com/learn/tutorials/topics/user-interface-ui much better once you start doing more complex stuff with it
Doh! Well that fixed it! Thanks mate! Seriously hate being a noob at this. I'll check out the new UI system here shortly. Thanks again.
Also check out this tutorial : https://unity3d.com/learn/tutorials/projects/survival-shooter-project its got all the info and coding and explanations you will need
djgriff, Thanks for the link. I've actually done all but two of the Unity tutorials including the survival shooter. But they were using triggers as colliders from what I remember and can see within the scripts. Also, maybe it is just me but I have a really hard time going back to those tutorials and finding the parts I need to refresh my memory.
you may also find that trigger vs collider is moot for fast projectiles... you can get into a situation where the object is moving faster than the physics engine can work out what it has hit so it passes through things when it shouldn't. In which case you'll need to switch to raycasts. Seb's done a really nice series which does that: https://www.youtube.com/playlist?list=PLFt_AvWsXl0ctd4dgE1F8g3uec4zKNRV0 (think it's no.2 gun in particular)
LeftyRighty, Thanks for the link, I'll add it to the many things I need to research and learn. I'm still new but I constantly hear about raycasts, so I'll definitely need to look into them sooner rather than later.