- Home /
variable returns from referenced script as 0
I try to reference a variable in another script and it comes back as 0, no idea why, here's my code
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "candy")
{
candyKainz++;
other.gameObject.GetComponent<Candycaine>().collected();
}
}
public class Counter : MonoBehaviour {
public Text numeber;
public Characterbehavior h;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
numeber.text = h.candyKainz + "/100";
}
}
What does the collected() function do? It would be a lot more clear if we had the actual class that does the math.
As far as I can tell, you're never assigning "h" in your code above. So I'm assu$$anonymous$$g that "h.candy$$anonymous$$ainz" would return 0 by default.
If "Characterbehavior" is on the same object as "Counter", then you may want to do h = GetComponent<Characterbehavior>()
on Start().
Wow I couldnt really see that. His code is a bit difficult to read. I think that is definitely a huge problem. He should set h's candy$$anonymous$$ains in the OnTriggerEnter2D function maybe
They may have several classes on the same script, which can be okay in some cases. In the OnTriggerEnter2D function, they only increase an internal number (some kind of score I'm assu$$anonymous$$g), and tell the pickup item to set itself to "collected", which might mean playing a sound, particle, and despawning. So the code isn't actually wrong, it's just formatted a little weird in their original post.
Cheers,
~LegendBacon
Answer by sisse008 · Jan 10, 2018 at 12:23 PM
you are not referencing a variable anywhere in the code you posted. you are referencing a Candycaine component with the line:
other.gameObject.GetComponent<Candycaine>().collected();
and calling a function (collected()) in the Candycaine component.
for us to help you, please post both scripts and mention which variable you are referring to.
Answer by creganjordan292 · Jan 10, 2018 at 12:55 PM
Your "Characterbehavior" needs to be assigned. If it extends a MonoBehaviour, you can add this through the inspector or calling a "GetComponent" on a GameObject which does have one. Other wise you use: h = new Characterbehavior()
to create a new instance and assign candyKainz before you try to read the variable.
Your answer
![](https://koobas.hobune.stream/wayback/20220612150204im_/https://answers.unity.com/themes/thub/images/avi.jpg)