I’m trying to use Vector2.Distance to find the distance between two gameObjects in 2d, but I can’t figure out the syntax & none of the answers I’ve found give me an explanation of how to reference the gameObjects in question. Let’s call the two objects “gameCube” & “gameSphere”.
var distance = 0.0000000;
function Update () {
distance = Vector2.Distance(gameCube.transform.position, gameSphere.transform.position);
}
This didn’t work, so I tried listing the gameObjects as strings:
distance = Vector2.Distance("gameCube".transform.position, "gameSphere".transform.position);
It just tells me ‘transform’ is not a member of ‘string’.
Finally I tried listing the game gameObjects as variables:
var gameCube = GameObject;
var gameSphere = GameObject;
var distance = 0.0000000;
function Update () {
distance = Vector2.Distance(gameCube.transform.position, gameSphere.transform.position);
}
& that just tells me ‘transform’ is not a member of ‘system.type’
Am I missing something? Any help would be much appreciated ;-;
First of all, make sure you keep the windows rolled up and the doors locked when you’re writing JavaScript.
Here’s an example of computing the 2D distance between two things and putting the result into a text field.
#pragma strict
var t1: Transform;
var t2: Transform;
var output: UnityEngine.UI.Text;
function Update() {
output.text = '' + UnityEngine.Vector2.Distance(t1.position, t2.position);
}
Drag the two things you want to measure the distance between into the editor boxes in the inspector for the appropriate instance of the script as well as the label to hold the result.
In the third block, you are not correctly declaring your GameObjects.
The lines you have written mean:
var gameCube = GameObject; // gameCube is now equal to the GameObject TYPE
var gameSphere = GameObject; // gameSphere is now also equal to the GameObject TYPE
Note that neither of these ARE GameObjects. They are the effectively nicknames for the TYPE GameObject
.
The first error is telling you that the GameObject
type itself does not have a .transform
component (but objects of type GameObject
do).
In your second block, you are trying to find the .transform
of a string
, which also doesn’t exist.
You should use:
var gameCube : GameObject; // gameCube is now an object OF type GameObject
Then your first attempt to find the distance will work.