I spent half a day finding how to change value one prefab NOT ALL
This is my example:
First, I attach this script “Enemy_Health” to the enemy prefab:
//My enemy's health is 2
static var HEALTH = 2;
Second, I tag my prefab enemy “enemy”, then attach this script to my bullet:
function OnTriggerEnter(hit : Collider) {
if(hit.gameObject.tag=="enemy")
{
//get the script "Enemy_Health" and then subtract the health of enemy from the script
var enemy : Enemy_Health = gameObject.GetComponent(Enemy_Health);
enemy.HEALTH -=1;
//Destroy only an enemy prefab collider, not all prefab
if(enemy.HEALTH <=0)
{
Destroy(hit.gameObject);
}
}
}
I don’t know my script didn’t work as my expectation( change value HEALTH one prefab and destroy that prefab NOT ALL ).
In this case, kill the enemy after shooting 2 times
On contrast, what my script did is when my bullet hit the obJect, other instantiating enemyprefabs are destroyed immediately and other left over enemyprefabs in my screen game are destroyed by only ONE buttlet, not 2.
You have the variable HEALTH marked as static. Normal variables ‘exist in their instance’, meaning that if you have two enemies with the script
var health : int;
then you can set the health of one of them to 50 and the health of the other to anything else.
Static variables however ‘exist in the scene’. There is only one of them at all times. I don’t know why you have HEALTH be a static variable in this case, but it does exactly what it does - if you change it in one instance of the script it changes for all.
I’m guessing the reason you did it here is so you can access it more easily? scriptName.theStaticVariable is how you access a static variable because for that scriptName there is only one version of theStaticVariable. If you want to access a normal variable you have to get it from that instance of the script using GetComponent.
[edit] here’s what it should look like. The first script is called Enemy_Health, the second is called whatever you want.
var health : int = 2;
that’s the first, then the second:
function OnTriggerEnter( hit : Collider )
{
if( hit.GameObject.tag == "Enemy" )
{
var enemyHealth : int = (hit.gameObject.GetComponent( Enemy_Health ) as Enemy_Health).health;
enemyHealth--;
if( enemyHealth <= 0 )
{
Destroy( hit.gameObject );
}
}
}