I’m going for a very simple RPG-type minigame here. This is the essence of my “enemy” script, in which I set the enemy’s trigger as the “battleRange.” When the player is inside an enemy’s battle range, it can “hit” the enemy with the space bar and deplete its HP. It works as expected, except for one detail: when I start the game, the bool is set to “true,” allowing the player to spam the space bar as soon as the game starts and kill the enemy without getting close to it (obviously no good). Nothing I have tried works to initialize it to “false” on startup (I’ve tried A: initializing it as battleRange=false, as well as battleRange=true, just for kicks, B: initializing it in the Start function instead, C: leaving it uninitialized at all). I’m sure I’m doing several things wrong, as I still don’t totally understand OnTriggerEnter/Exit. Should I be putting parts of this on the player rather than the enemy? All suggestions welcome, thank you kindly!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float enemySpeed = 3;
Rigidbody enemyRB;
GameObject player;
public bool battleRange = false;
public int hP = 5;
void Start()
{
enemyRB = GetComponent<Rigidbody>();
player = GameObject.Find("PLAYER");
//battleRange = false;
}
void Update()
{
enemyRB.AddForce((player.transform.position - transform.position).normalized * enemySpeed, ForceMode.Impulse);
if (Input.GetKeyDown(KeyCode.Space) && battleRange)
{
hP -= 1;
}
if (hP < 1)
{
Destroy(gameObject);
}
//Debug.Log(hP);
Debug.Log(battleRange);
}
private void OnTriggerEnter(Collider other)
{
battleRange = true;
}
private void OnTriggerExit(Collider other)
{
battleRange = false;
}
}