- Home /
Unable to access variable from other C# script?
I'm making a FPS and I have two scripts. "p_stats" is the statistics for the player (ammo, health, abilities, etc.) and "p_weaponmech" is the script that will change the gun based on class and make the gun fire. For some reason, though I have public variables, it completes the math equation from the p_stats script but fails to see the value in the p_weaponmech script.
p_stats
public class p_stats : Monobehaviour
{
public int a_main;
public int a_perclip;
public int a_clips;
void Start ()
{
a_main = a_clips * a_perclip;
Debug.Log(a_main.ToString());
}
}
p_weaponmech
public class p_weaponmech : Monobehaviour
{
private GameObject p_obj;
private p_stats stats;
private int p_ammo;
void Start
{
p_obj = GameObject.Find("Player1");
p_stats = p_obj.GetComponent<p_stats>();
p_ammo = p_stats.a_main;
}
}
I've done several "Debug.Log" statements to see if the object was found, if the script was found, etc. and that apparently was not the problem. Any ideas?
Answer by UnityCoach · Dec 05, 2016 at 02:01 PM
You assign p_stats, which is a type, not the member you declared. Try :
stats = p_obj.GetComponent<p_stats>();
p_ammo = stats.a_main;
I would also encourage you to follow C# naming conventions, class names begins with Upper case, members camelCase, private members begin with an _underscore, etc..
It should make things easier to catch. My two cents.
The underscore for private members is not the official C# na$$anonymous$$g convention but quite popular. I also can't find any logical reason what "a_" and "p_" would mean in this context ^^.
I usually use the prefix "a" for arguments in methods. This simplifies the assignment of local variables with the same name ^^. I'm usually close to the "official" na$$anonymous$$g convention with a few exceptions.
Even though it contradicts the na$$anonymous$$g convention, I do like to tell at a glance if a variable is a member variable. I do see the issues with it, though, such as a higher chance of variable shadowing. Using it in type and member names seems odd, though.
I'm so dumb! I was coding this at midnight and I was so confused as to why it wouldn't work. Thanks so much for your help my dude!
no worries, happens to the best of us ;) That's why I suggested using a clear na$$anonymous$$g convention. It actually helps to spot these kind of mistakes.
Your answer
![](https://koobas.hobune.stream/wayback/20220612102034im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Access variables from other Script via Properties [C#] 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Script can't find Component within Start() - C# 1 Answer
Framerate doubles when pausing and unpausing editor 0 Answers