- Home /
GetComponent Help
I'm pretty new to the getcomponent function in java and I want to learn it,I did not understand the unity docs, so here I am, How do I make an getcomnponent to my player and a script called moneysystem and access the int called money in the system? i got my code to give me money here
#pragma strict
var Health = 100;
var tombstone : GameObject;
thePlayer : GameObject;
function ApplyDammage (TheDammage : int)
{
Health -= TheDammage;
if(Health <= 0)
{
Dead();
}
}
function Dead()
{
Instantiate (tombstone, gameObject.transform.position, Quaternion.identity);
/*GET COMPONENT HERE
--------------*/
Destroy (gameObject);
}
and here's my money code
var money : int = 1000;//amout of your money
function Update()
{
if(money < 0)
{
money = 0;
}
}
Answer by Kiwasi · Jul 29, 2014 at 08:47 AM
Are the two scripts on the same GameObject? If they are you can eliminate the find step. (code is C#, but the principle is the same).
GameObject moneyObject = GameObject.Find("MoneyObject");
MoneyScript moneyScript = moneyObject.GetComponent<MoneyScript>();
moneyScript.money = 0;
In general you want to use Find and GetComponent as little as possible, they are expensive functions. You can often do this by calling them once in start and hanging onto the result.
Your answer
Follow this Question
Related Questions
Referencing a c# component script from JS script 2 Answers
Create a if statement using GetComponent? 1 Answer
NullReferenceException. GetComponent not working? 0 Answers
Problem accessing script 2 Answers
Referencing booleans from settings 1 Answer