- Home /
Problem with getting component, help please? ^^'
Hi I've got some trouble lately trying to use getcomponent.
Could I have some information on what makes my C# script not working please? ^^'
static Component skillLvlVal;
static Component skillCurVal;
void GetValues() {
skillLvlVal = transform.parent.gameObject.GetComponent("LvlVal");
skillCurVal = transform.parent.gameObject.GetComponent("CurVal");
}
static int lvlVal = int.Parse(skillLvlVal.GetComponent<GUIText>().text);
public static int currentVal = int.Parse(skillCurVal.GetComponent<GUIText>().text);
static int minHp;
static int maxHp;
static int hp;
static void Start () {
GetValues();
minHp = 0;
maxHp = lvlVal;
hp = maxHp;
}
This is only a part of the script, but the rest isn't necessary as it's not yet using those values, but will as soon the error is fixed ^^.
Basically I'm trying to get a component (LvlVal and CurVal) from the script parent. But when calling it, it gives me an "Object not set to an instance of an Object." for each of the two Values.
This script is to make a basic Skill tree. (Here's the screen shot to show what it looks like, I got a button on the second button (second in the top row))
Here's how the button looks like, the CurVal is the top number and the lvlVal is the bottom one.
Could I get some help with that please ? ^^
Answer by tanoshimi · Jan 10, 2017 at 07:05 AM
This line gives you an "object not set to an instance of an object"?
skillLvlVal = transform.parent.gameObject.GetComponent("LvlVal");
That would suggest that the object to which this script is attached does not have a parent.
As a separate issue though, you seem to be making all your variables static
- why is that? It's undoubtably going to cause you troubles later on.
would there be a better way to do it? ^^ (I'm kinda new to c# coding ^^') Here's the error it gives me when I remove the statics:
Oh, I think I found what you meant by no parent. It tries to get the parent of object that has the script on.
Now I get it. ^^ Still trying to fix it, but yea... now I understand a bit more ^^.
Well, the better way to do it would be to not make those variables static unless you really think they need to exist at the class level rather than at the instance level.
Thx for the help ^^. $$anonymous$$y brother came in and explained exactly why it didn't work. Now it gets everything correctly ^^.
Thx again. You helped me understand what was the mistake in my code. Anyway, gonna get back to learning a bit more before continuing this script I think ^^.