I admit to being more used to JAVA than C#. A student working on a project has hit me with a problem and I can’t seem to solve it.
The basic idea is to have Droid run around and gather scrap bits. To make this possible he’s created one cs file that’s more or less like this one:
public class Scrap : Monobehaviour {
public int scrapValue;
...
}
He’s attached this code to several objects in a unity window.
public class Droid : Monobehaviour {
public doSomething() {
GameObject closest = searchClosest();
print (closest.name + "-" + closest.scrapValue;
}
We’re getting an error in that none of the methods we can think of based off the online info seems to work. The name will appear but no value. In fact, if we take closest.name off, we get null.
Public variables have global visibility, but since you may have several instances of the same script, the name alone isn’t enough to access the variable. There are two ways to access the variable scrapValue:
1- If you want to have only one scrapValue, you can declare it as static:
public static int scrapValue;
A static variable is equivalent to a global variable in non-OOP programming: the variable is the same for all scripts, even if there are several instances of the script where the variable was declared - actually, the variable is created when the program begins, even before any instance of such script exists, and survives until the program ends.
You can access the static variable above as Scrap.scrapValue (className.variableName).
2- If you may have several independent scrapValue variables, you will need a reference to the particular instance of Scrap that you’re interested in, or use a reference to its owner object to get the script reference. If closest is a the reference to the GameObject you want, get Scrap with GetComponent:
GameObject closest = searchClosest(); // find the object
Scrap scrapScript = closest.GetComponent< Scrap>(); // get its Scrap script
print (closest.name + "-" + scrapScript.scrapValue); // access scrapValue