- Home /
Script Referencing
Could someone explain me how do I use one scripts elements in other scripts (GetComponent), and also help me with following script ?
Here's the script cameraSwitcher.js :
var MainCamera : Camera;
var FPCamera : Camera;
var Active : boolean = false;
function Start(){
MainCamera.enabled = true;
FPCamera.enabled = false;
}
function Update(){
if(Input.GetKeyDown("tab") && Active == false)
{
MainCamera.enabled = false;
FPCamera.enabled = true;
Active = true;
}
else if(Input.GetKeyDown("tab") && Active == true)
{
MainCamera.enabled = true;
FPCamera.enabled = false;
Active = false;
}
}
I want to create second script that would control whether the gameObject I choose is visible or not.
So, if MainCamera is enabled gameObject.renderer is enabled too.
And, if MainCamera is disabled gameObject.renderer is also disabled.
I just don't understand how to do it I looked for scrpiting reference on Unity's site but I still can't quite figure it out.
Answer by aldonaletto · Nov 06, 2011 at 05:01 PM
Firstly, you could simplify the Update function of cameraSwitcher.js this way:
function Update(){ if (Input.GetKeyDown("tab")) { Active = !Active; MainCamera.enabled = !Active; FPCamera.enabled = Active; } }You have two ways to access Active from other scripts:
1- If there exists one only cameraSwitcher instance in your program, you can declare the variable Active as static in cameraSwitcher.js:
static var Active: boolean = false;
then access it in other scripts like this:
if (cameraSwitcher.Active){
2- If you have other instances of cameraSwitcher, you must have some reference (transform, collider, gameobject etc.) to the object whose Active variable you're interested in. You can have a Transform variable in the other script and assign the object in the Inspector:
other script:
var camSwitcherObj: Transform; // drag the object here
var camSwitcher: cameraSwitcher; // this will contain the script reference
function Start(){ // get a script reference at Start to save time
camSwitcher = camSwitcherObj.GetComponent(cameraSwitcher);
}
// then you can use camSwitcher as the script reference:
if (camSwitcher.Active){
I figured out i could do this without any script reference, but this was useful in my other script
Answer by Fabkins · Nov 06, 2011 at 04:49 PM
You can use GameObject.Find("object_name") to get a reference to the object.
// object_name is the name you've given the object in the inspector
myobject=GameObject.Find("object_name");
You can then do whatever you like to it...
myobject.transform.y += 10; // moves it up 10
myobject.active=false; // makes it inactive
Your answer
Follow this Question
Related Questions
Reference Not Set toInstance of Object 1 Answer
Can I access a script referenced in another script (without getcomponent)? 5 Answers
Is performance related to the script size that is called by GetComponent? 1 Answer
Can Only Reference My Own Scripts 1 Answer
Accesing script from newly instantiated game object 1 Answer