- Home /
Set variable in script from a different script...
Hey guys,
I was wondering, how do i set the variable of a script from a different one....?
I know i have to use something like this:
var objectWithOtherScript : GameObject;
function Update(){
objectWithOtherScript.GetComponent("scriptName")..........
}
but i don't know what to do after that.....
Any help would be greatly appreciated!!!!
-Grady
Answer by Joshua · Jul 08, 2011 at 01:56 AM
Please use search in the future, this has been asked and answered many times. Second of all, you ussually want to use GetComponent.() instead of GetComponent( T );
Say you have script1 with only one line in it:
var someVariable : int;
To change this variable from scrip2 you write, in the second script:
objectWithOtherScript.GetComponent.< script1 >().someVariable = someNumber;
it says that it's unnaccessable because of it's protection level...
then you should make the variable public.
To access from different script:
public var someVariable : SomeType;
and Not: private var someVariable : SomeType;
Is there a C# version of this code? I am getting some problems saying that it's cannot be accessed with an instance reference, qualify it with a type name ins$$anonymous$$d.
hit.transform.GetComponent< ScriptB >().setBool = true;
The bool is a public static variable.
is "ScriptB" a name of a type (class, variable, struct etc) or is it the name of the instance?
Cause it seems from the error you are getting you are using the name of the instance ins$$anonymous$$d of the name of the type.
Answer by Hunden · Aug 16, 2014 at 09:29 PM
void SpawnPlayer(){
GameObject player = (GameObject) Network.Instantiate(playerPrefab, new Vector3(0f, 4f, 0f), Quaternion.identity, 0);
//set the camera
SmoothFollow script = (SmoothFollow) Camera.main.GetComponent("SmoothFollow");
script.target = player.transform;
}
Here's how i did it in C#.
Answer by Vinny-the-true · Oct 04, 2017 at 08:44 AM
OK, this is nice, but how can we do this from the inspector ?
What I ant to do is exactly what is done by the AnalyticsTracker with its parameters, so we may be able to select an object and then one of its property exactly the way you do it with UnityActions but with fields instead of methods !
Your answer
Follow this Question
Related Questions
How to deactivate something when holding down a key? 1 Answer
How do I change the text of a GUIText object through another GameObject using a variable? 2 Answers
Similar set of variables between classes... 2 Answers
how can I display a variable as a GUIText 5 Answers
How can I access a variable from another script in a separate object? 1 Answer