- Home /
Repeat While Object in Range
I am using a version of Unity 4, kind of old, I am looking at updating it. I am a beginner still and I have barely learned the old version, the new version seems just that much more complicated. My code has a sphere collider on an enemy, and I want it to constantly take 1 health from the player while the player is within the enemies circle. I turned the sphere to "On Trigger", it doesn't work. here you go.
public class MogiAI : MonoBehaviour {
public GameObject player;
public float MovementSpeed = 2;
public bool IsMoving = true;
bool Triggered = false;
public float testhealth = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (IsMoving == true){
transform.position = Vector3.MoveTowards (transform.position, player.transform.position, MovementSpeed * Time.deltaTime);
}
transform.LookAt (player.transform.position);
if (Triggered == true) {
testhealth = testhealth - 1;
}
}
void OnTriggerEnter (){
Triggered = true;
}
void OnTriggerExit (){
Triggered = false;
}
}
First, check the signature of OnTriggerXXX
: https://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.OnTriggerEnter.html
Then, make sure the collisions are detected (using Debug.Log
) if not, follow carefully the tutorials on the Unity website.
Answer by aldonaletto · Jun 27, 2017 at 12:24 AM
You must attach a Rigidbody to the player and set its Is Kinematic checkbox to make it visible to triggers: a kinematic rigidbody is visible to the physics engine but doesn't react to forces, collisions, gravity etc.
NOTE: By the way, your player will drop dead in one second or less if you subtract 1 from its health every Update. Multiply the health loss per second by Time.deltaTime in order to get a constant speed:
if (Triggered == true) {
testhealth -= 2 * Time.deltaTime; // player loses 2 units per second
}