- Home /
Accessing Scripts and Their Variables from other Objects
I am trying to look at a float from a Script that is contained in another object (or on a few objects). The Character Controller I set up has this to read a variable (HealthRatio) to use to show to the player how much health (via healthbar) the enemy has.
if(Tag == "Enemy") { EnemyStats = hit.collider.gameObject.GetComponent("EnemyScript"); EnemyHealth = EnemyStats.HealthRatio; EnemyHealthBarLength = BarLength * (EnemyHealth); }
However, Unity declares that the "*" cannot be on the left handside of the Object "EnemyHealth." It seems that EnemyHealth isn't set as avariable, but as a GameObject. I tried using GetComponent, but obviously it did not work as I desired.
Thank you for the help.
format code with the 10101 button post EnemyScript and post where BarLength is decalred and set.
It APPEARS the problem is the game has no idea how to multiply those 2 objects.
The problem for helping you is this is JavaScript not C# so I can't see what type an object is without seeing the declaration.
Answer by PAEvenson · Nov 21, 2012 at 07:58 PM
you need to typecast the component to the variable you want it to be `hit.collider.gameObject.GetComponent("EnemyScript") as EnemyScript;`
it finds out variable types by itself and force casting shouldnt normally be done unless you know its safe just post some code up man so we can see whats wrong.
Your saying a * b doesn't work wihtout showing a or b
add in formatting as well.
Answer by Hi_No_Te · Nov 21, 2012 at 11:37 PM
Here's the posting of the area that's giving me trouble and BarLenght.
if(Tag == "Enemy") {
EnemyStats = hit.collider.gameObject.GetComponent("EnemyScript") as EnemyScript;
EnemyHealth = EnemyStats.HealthRatio;
EnemyHealthBarLength = BarLength*(EnemyHealth);
Here's BarLenght's declaration:
var BarLength : float = 380;
And EnemyScript:
var Health : float;
var Stamina : float;
var Mana : float;
var CurrentHealth : float;
var CurrentStamina : float;
var CurrentMana : float;
static var HealthRatio : float;
static var ManaRatio : float;
static var StaminaRation : float;
function Start () {
if(gameObject.name == "Capsule") {
Health = 120;
Mana = 120;
Stamina = 120;
CurrentHealth = 100;
CurrentMana = 120;
CurrentStamina = 120;
HealthRatio = CurrentHealth/Health;
ManaRatio = CurrentMana/Mana;
StaminaRation = CurrentStamina/Stamina;
}
}
function Update () {
}
Answer by Hi_No_Te · Nov 22, 2012 at 06:56 PM
I figured it out, and I did not post it:
private var EnemyHealth : float;
private var EnemyMana : float;
private var EnemyStamina : float;
I did not add the ": float: and it took each as an object. As soon as I replaced it, it worked.