I am trying to have a numerical variable from the player transfer to another object when the player enters that object’s trigger. On the other object’s script I used this code in an OnTriggerEnter function:
if (object.transform.name == "Player") {
var addpoints = GetComponent("/Player.points").pCount;
totalpoints += addpoints;
The “totalpoints” part is defined earlier in the above script. Unity accepts the code, but when the player enters the trigger the console objects, saying “Object reference not set to an instance of an object” in reference to the line that starts “var addpoints” above.
I’m not sure why this is happening, but I am afraid it is a syntax issue.
Any ideas?
GetComponent should be used with the script name. That is, assuming there is a script named “Player” attached to the object, and a public variable pCount in this script:
GetComponent(Player).pCount;
Acouple of sides notes:
- With rare exceptions, you don’t need to use a string to get a component - only the class name itself, as shown above. In fact, using a string is slower. The only time you might need to use a string is getting scripts across languages (C# and JS)
- It’s considered bad form to directly access variables from a GetComponent call, as shown above. It’s better to store the component in a variable:
var playerComponent : Player = GetComponent(Player);
if (playerComponent) totalPoints += playerComponent.pCount;
In your example, this can (probably) be used to eliminate your overarching if statement, assuming the player object is the only one with the Player script attached.
Thanks, StarManta for your reply. I have been trying to understand and use the code there but I haven’t had any luck and still get the “not set to an instance” warning.
Oddly, I can make an object (a gate) tell the player to change one of the player’s variables. Like this:
var tellplayer = GameObject.Find("/Player");
tellplayer.GetComponent(points).gpoints = 1;
(“points” is the script and “gpoints” is the variable)
This is in a script on the gate and works fine. But when I try to turn it around and just get a value from the player’s variable and add it to a variable in the gate script itself, I can’t get it to work.
How can I take that “gpoints” variable from the player script and add it to a variable in the gate script?
Any advice? Thanks.
Sorry to keep posting on this but I spent several days of my game time on it with no luck and I finally found the answer in another forum post (linked below).
If anyone else has a problem with this warning:
“Object reference not set to an instance of an object” you should check out this reply by Jonathan Czeck. Thank you Jonathan! Now I can finish my game!!
http://forum.unity3d.com/viewtopic.php?p=16344&highlight=#16344