- Home /
Proper syntax for GetComponent
Im trying to access goldAmount on the mainScript thru the goldScript which is on the gold GameObject. I cant for the life of me figure out the GetComponent action. Here are my two scripts:
mainScript
var customStyle3: GUIStyle;
var size : Vector2 = new Vector2(60,20);
public var goldAmount : int;
function OnGUI()
{
GUI.Label (Rect(Screen.width /2 , 0, size.x, size.y), "Gold : " + goldAmount, customStyle3);
}
goldScript
function addGold()
{
//mainScript = GameObject.Find ("Main Camera").GetComponent(goldAmount);
//goldAmount ++;
//Destroy (gameObject);
}
function Start()
{
WaitForSeconds(3);
addGold();
}
For future posts, please format your code. After pasting, select your code and use the 101/010 button. I fixed it for you this time.
Answer by Ekta-Mehta-D · Aug 28, 2014 at 06:08 AM
Hello..
1) Create object of type "mainScript" in goldScript.
private var mainscriptObj : mainScript;
2) Get refference of this script.
mainscriptObj = GameObject.Find ("Main Camera").GetComponent(mainScript);
3) Now you can access goldAmount.
mainscriptObj.goldAmount++;
Thanks.
You can do tick mark on my answer if it works for you.
Answer by RedDevil · Aug 28, 2014 at 06:10 AM
You cannot acces the gold amound like this
mainScript = GameObject.Find ("Main Camera").GetComponent(goldAmount);
GetComponent is meant for getting components of an object.Like getting the transform property or a script but definetly not a variable from that script. Try like this:
var MainScript = GameObject.Find ("Main Camera").GetComponent("mainScript");
//i would change the variable named mainScript too so there are no confusions...
//then you acces it through the MainScript object
MainScript.goldAmount = 100;
Answer by Aresak · Aug 28, 2014 at 08:02 AM
C#
GameObject.Find("Main Camera").GetComponent<mainScript>().goldAmount = 100;