I learnt a bit of C++ a long time back and am now trying to understand the equivalent of ‘pointers’ in Javascript, which I am trying to learn with Unity. I guess this is also a query about efficiently referring to variables in other scripts that I don’t want to make available using static .
I created TargetFinderScript.js which I attached to a gameobject. I wanted this script to access a variable
chasetarget : GameObject
in script BallUpdateScript.js, which is on the same gameobject.
So in TargetFinderScript.js I thought I would declare a variable
var chasetarget2 : GameObject
and assign chasetarget2 to chasetarget, using the GetComponent() function.
This worked, but I pretty soon realised that chasetarget2 was not a reference to chasetarget i.e. like a ‘pointer’, but a completely new GameObject. Making changes to chasetarget2 did not affect chasetarget.
Is there a way to easily create some kind of local reference in the way I am envisaging that I am overlooking, or do I need to just call the GetComponent() function every time I want to refer to something in another script?
Note: I’m aware of the SendMessage() function as well but this seems equally cumbersome.
After further investigation I’ve found that the following allows me to reference chasetarget by referring to bscript.chasetarget
However, the following code doesn’t work in that making changes to chasetarget2 doesn’t affect chasetarget. In the first example it is obviously passing by reference, in the second it is passing by value???
You’re right, all is well in the world: I’ve now realised that I wasn’t correctly understanding what was going on - and have proved to myself that chasetarget2 is indeed being passed a reference type to chasetarget, a gameobject, if and when chasetarget is not null.
I think my fundamental mistake is that I didn’t understand that I didn’t actually need/want to get a reference to gameobject and then manipulate it, rather what I really wanted to do was manipulate the variable which is as I understand “a property of the BallUpdateScript class”, and which could hold one of a number of different gameobjects.
I was trying to change which gameobject the reference was to, so I don’t want the gameobject, I want the property, so I’m guessing that referring to bscript.chasetarget is the only way to refer to this.