Hi guys,
im not sure if this is the correct terminology. But what I am trying to do is… I have a health bar connected to a tower. When a unit is near it decreases. Works great. But when I have multiple of the same tower on the screen its buggy. I think its because I am using the same variable for both towers. How do I make it so their variables are not shared? I have my code below with comments. It is applied to the “towers” in my game.
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour
{
private int testInt=0; // Update is called once per frame
public Texture2D selectionHighLight = null;
private Vector3 captureBarPos = Vector3.zero;
private static float captureBarLength = 500f;
private static float maxCaptureBarLength =500f;
private static float length = 50f;
public bool playerCapture =false;
void Update(){
captureBarPos = Camera.main.WorldToScreenPoint (transform.position);
print("target is " + captureBarPos.x + " pixels from the left");
if(captureBarLength>=0){ //this is the code that captures faster based on amt of units in area
switch(testInt){
case 1: captureBarLength-=1;
break;
case 2: captureBarLength-=2;
break;
case 3: captureBarLength-=3;
break;
}
//test
if(captureBarLength<3){//just a test to see color change
playerCapture=true;
}else{
playerCapture=false;
}
}
if (captureBarLength <= maxCaptureBarLength && testInt == 0) { //refill bar when no units around
captureBarLength+=5;
}
if (playerCapture == true) {
renderer.material.color = Color.red; //change color when captured
} else {
renderer.material.color = Color.white;
}
}
void OnTriggerEnter(Collider col) { //detecting if "unit" is in the area
if(col.collider.gameObject.name=="Unit"){
testInt+=1;
Debug.Log(testInt);
}
}
void OnTriggerExit(Collider col) { //detecting if "unit" is in the area
if(col.collider.gameObject.name=="Unit"){
testInt-=1;
Debug.Log(testInt);
}
}
private void OnGUI(){
GUI.DrawTexture(new Rect (captureBarPos.x-30,(Screen.height-captureBarPos.y)-50,length*(captureBarLength/maxCaptureBarLength),5),selectionHighLight);
}
}