Hello everyone!
I am trying to change a variable which is located in another script.
Does anyone know how I can do this?
I have already checked the Script Reference and some other questions but they either use C# or I just can’t seem to be able to implement their examples.
Here is an example of two scripts and how I am trying to access a variable from SCRIPT02.js:
// >>>>>>>>>>
// SCRIPT_01.js
#pragma strict
function OnMouseDown () {
var imported_script02 : SCRIPT02;
imported_script02 = GetComponent("SCRIPT02");
click_count++;
}
function Update () {
var imported_script02 : SCRIPT02;
imported_script02 = GetComponent("SCRIPT02");
if ((click_count) == 10) {
Debug.Log("mouse has been pressed 10 times");
}
}
// <<<<<<<<<<
// >>>>>>>>>>
// SCRIPT02.js
#pragma strict
var click_count : int = 0;
// <<<<<<<<<<
Many thanks in advance for any help!
First of all, thank you very much for your help!
I tried to access the variable now in that way, but the Console says:
“NullReferenceException: Object reference not set to an instance of an object”.
At the point I try to change the variable, the second object (which holds the second script) will disappear from the Inspector’s Script-tab of the first object.
Any ideas what could cause this problem? Maybe I misunderstood something?
EDIT:
I solved the problem now.
“var click_count : int = 0;” has to be a static variable. I only used var and public var when testing it.
Also,
var imported_script02 : SCRIPT02;
imported_script02 = GetComponent("SCRIPT02");
can be used outside of the functions so that it’s not required several times.
So, if someone has the same problem, the right way to do this is:
// >>>>>>>>>>
// SCRIPT_01.js
#pragma strict
var imported_script02 : SCRIPT02;
imported_script02 = GetComponent("SCRIPT02");
function OnMouseDown () {
imported_script02.click_count++;
}
function Update () {
if ((imported_script02.click_count) == 10) {
Debug.Log("mouse has been pressed 10 times");
}
}
// <<<<<<<<<<
// >>>>>>>>>>
// SCRIPT02.js
#pragma strict
static var click_count : int = 0;
// <<<<<<<<<<