- Home /
How to access this variable?
In this part of my script, there is a variable called colliders. A ray is cast to find the colliders and it finds all of them in a certain radius.
Some colliders have different scripts in them, but each of those different scripts share a variable called SystemHealth. How can I access that variable even though some colliders don't have any scripts and some of the scripts have different names?
Another way to word the question: How can I find the variable SystemHealth inside of the colliders. Here is the important part of the script.
function Explode() {
var colliders : Collider[] = Physics.OverlapSphere (transform.position, radius);
for (var collider : Collider in colliders) {
var hit : RaycastHit;
if (Physics.Linecast(transform.position, collider.transform.position, hit)) {
if (hit.collider == collider) {
if (hit.rigidbody)
hit.rigidbody.AddExplosionForce(power - (power / hit.distance), transform.position, radius, 3.0);
}
}
}
}
Answer by KMKxJOEY1 · Mar 31, 2013 at 11:21 PM
hit.collider.gameObject.GetComponent<SystemHealth>().fuction name here();
In js I think it's
hit.collider.gameObject.GetComponent(SystemHealth).function name here();
Note that the script name is not SystemHealth. It's just a variable that may or may not be inside the colliders. I'll try it out but I think the javascript is wrong. $$anonymous$$aybe I know how to fix it.
Edit: Yeah I added in:
print(hit.collider.gameObject.GetComponent(SystemHealth));
and it calls SystemHealth an unknown identifier.
oh lol then replace systemHealth with the script name
var health = hit.collider.gameObject.GetComponent(script
name).SystemHealth;
Answer by whydoidoit · Mar 31, 2013 at 11:50 PM
They don't share the the variable - just because they have the same name - it's not the same variable. If you want to share a variable you need to have a script with the shared variable that the other scripts access using GetComponent
I know they don't share the value, but they share the name. None the less, how can I access it in colliders? I tried to do:
print(hit.collider.gameObject.GetComponent(SystemHealth));
but that told me that SystemHealth is an unknown identifier.
Your answer
![](https://koobas.hobune.stream/wayback/20220613095437im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Variable Not Changing. 0 Answers
Should I create local copy of global variable? 3 Answers
How to make a GLOBAL variable in javascript (Unity) 0 Answers