- Home /
Other
Need help accsesing a scripts variable alfter getting the script cached.
Here is my code
#pragma strict
var Running = false;
function Start () {
}
function Update () {
}
This is the code that I want to change the variable Running to true.
#pragma strict
var CarScript : UnityEngine.MonoBehaviour;
function Car () {
}
This is the code to change the variable. So what the var CarScript : UnityEngine.MonoBehaviour; dose is gets the gameobject and its script.
So now I have the script cached now I need to accses the variable.
I tried to have It like Carscript.Running = true; but it didn't work.
any help?
Answer by toddisarockstar · Apr 15, 2015 at 12:41 AM
it took me awhile to figure this out too. i couldnt get responses and finally figured it out myself. anyways, depending on whether you are building for web,flash or standalone there are simpler ways of accessing other script, but here is the way i found to work with all. its kinda weird but always works. if you want to declair your variable above Update it looks like this:
//get an object with the desired script attached!!!
var car:GameObject;
car = gameObject.Find("car");
// assign the variable to expect the script component you are looking for!!!
var cs: nameofcarscript = car.GetComponent(nameofcarscript);
// now we declaired the component variable type so now we can actually assign it to the car
cs = car.GetComponent(nameofcarscript);
function Car () {
cs.goreallyfast=true;
}
#pragma strict
var CarerCar : GameObject;
var CarScript = CarerCar.GetComponent(Car);
CarerCar = gameObject.Find("Car");
function Car () {
CarScript.Running = true;
}
This is what I have done but I get an error at the CarerCar = gameObject.Find("Car");.
The error says. Assets/CarereChoser.js(3,38): BCE0023: No appropriate version of 'UnityEngin.GameObject.GetComponent' for the argument list '(function(): void)' was found
This game is a tycoon game btw and not a racing game. to shed more light on this. the game is were you chose what career you want to do and live in a real life economic situation trying not to lose money.
sorry for delay, if you havent allready got it, switch the 2 lines like this so the second variable knows what you are talking about:
#pragma strict
var CarerCar : GameObject;
CarerCar = gameObject.Find("Car");
var CarScript = CarerCar.GetComponent("Car");
function Car () {
CarScript.Running = true;
}
if you want to try it this way put quotes around "Car" if thats also the name of your script. that will get rid of the error. this way might work for a webplayer but pry idk about flash or standalone