- Home /
Too subjective and argumentative. Simplicity is in the mind of the beholder. Forum topic.
How can I simplify this script?
I made a script that detects if a certain object is near it every second and if so, it takes out health from the character and eventually they will re-spawn. I was wondering how I could make it so then it does the same with more than one tranform (so then it isn't just "enemy"). Is there any way I could do this with an array or a tag or something like that? This is the script:
var distance;
var enemy : Transform;
var attackDistance = 2;
var spawnPoint : Transform;
var health = 5;
var player : GameObject;
private var maxHealth;
function Start(){
maxHealth = health;
InvokeRepeating("Detection", 1, 1);
}
function Detection(){
distance = Vector3.Distance(enemy.position, transform.position);
if(distance < attackDistance){
(health) = (health) - 1;
}
if(health == 0){
Invoke("Respawn", 2);
player.SetActive(false);
}
}
function Respawn(){
player.transform.position = spawnPoint.position;
player.SetActive(true);
health = maxHealth;
}
You could put a sphere collider on this game object, and when the player is is (with OnTriggerStay() method), you decrement its health. This will avoid to check every second if it is close enough. Sorry but I don't have the time to give you some code :)
The trigger stay method should work, and rather than using involkRepeating you should use a Coroutine.
You can keep an array. If all your enemies are tagged, you could use GameObject.FindGameObjectsWithTag() either in Start() or every frame to get an array of game object and cycle through them. A better method would be to move the logic to the enemies. The enemies would detect when they are close to the player and then communicate to the player. See accessing other game objects.
The reason why I use InvokeRepeating is because there is because the enemy transform is following the character. If I used OnTriggerEnter, it would only do it once and the health would be 4 ins$$anonymous$$d of 5. By doing InvokeRepeating, as long as the enemy is close enough, it will take out 1 health every second. I am asking how I can make it work with more than 1 enemy.
@kyleyo9 - he suggested OnTriggerStay() which will fire every frame the colliders are touching.