- Home /
How to get the specific value from GameObject?
I'm trying to get how to make this. I have my collectible item which have special value But they all have one script and their value is typing in unity hierarchy How can I can the specific value in script?please explain Maybe "this" method or something like it...
Answer by SwedishDerp · Feb 23, 2018 at 08:31 AM
Not really sure what you are looking after but to recieve values and other commands from a gameobject with a script attached you can easily go with "GetComponent". Kinda like this:
public GameObject theObj;
public float Value;
public void Update(){
if(Input.GetKeyDown(KeyCode.E)
{
Value = theObj.GetComponen<The Script>().Value;
}
}
Thanks for your reply I have two values for different collectible objects And I type this values on the script component in the hierarchy The question is about how to get this specific values
You see, I have this two scripts if it might help! You can see that on the line 19 I'm using what your advice was
In the collectibles script you can not get the specific values by acessing the script itself, you need to have a owner.
Ins$$anonymous$$d of:
Score$$anonymous$$anager.score = this.score;
Use this:
col.GetComponent<Score$$anonymous$$anager>().score += this.score;
By doing this we are accessing the collider object's scripts :)
I have this static value, how can I change this to access?
public static int score;
Okay, so I changed the script like how you type it and change "public static int score" to just "public int score" But ins$$anonymous$$d of += this.score I think there must to be a += this.scoreValue right?
So here whats it look like now
//Score$$anonymous$$anager.score += scoreValue;
col.GetComponent<Score$$anonymous$$anager> ().score += this.scoreValue;
ScoreWorldText.printingScore = this.scoreValue;
Score$$anonymous$$anager.collected = true;
In the Game mode the score world text showing only 100 points And the error in the console appeared
No, no. But almost!
//Score$$anonymous$$anager.score += scoreValue;
col.GetComponent<Score$$anonymous$$anager> ().score += scoreValue;
col.GetComponent<Score$$anonymous$$anager>().printingScore = scoreValue;
col.GetComponent<Score$$anonymous$$anager>().collected = true;
You see, the GetComponent function needs an owner with this script and in this case it's the collider (col). You can google further on the "GetComponent" function :) Sorry if I'm unclear
Answer by Vencarii · Feb 26, 2018 at 09:23 AM
Wouldn't it be better to have Collectibles script with a List or Array that holds all the Collectible objects instead of two instances of that Script on the GameObject?
Is that will be easier? I'm not so good in scripting for now, don't know many things :) I need just to make the collectibles to show specific value, and not updating this value when other collectible is collected because it have his own score text to be shown.