How to find the x and y axis of a gameobject

How can I find the x and y axis of a gameObject in script, so I can check whether the object is above or below a certain height? for example if the gameObject drops below 100 meters, it triggers something.

any help or advice would be great

thanks in advance

if (transform.position.y <= 100) {
//Do stuff
}

That’ll work for both C# and ā€œJavaScriptā€/UnityScript.

This is very basic stuff; I’d recommend some tutorials before you go much further into Unity.

2 Likes

thank you

I do when I can find them, most are just repeats of others.

beennn
I think you could use a custom c# function like this:
public float getXAxis(){
return transform.position.x;
}

and then call it whenever you needed.

This worked in previous games I worked on but now I use it and this is the error I get:

error CS1612: Cannot modify the return value of ā€˜Transform.position’ because it is not a variable

This is my code:

using UnityEngine;

public class RandomizeMissleSpawns : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        transform.position.x = Random.Range(-11, 12);
        Debug.Log(transform.position.x);
    }
}

You have to replace the whole position vector at once:

transform.position = new Vector3(
  Random.Range(-11, 12),
  transform.position.y,
  transform.position.z);

That being said, the position of this thing is going to jump around like crazy every frame!

It works! Thank you! and just so you know, I wanted it to go like crazy because I was moving a object to determine Missle Spawning. I also learned how to give a value to a Vector3 in code! Thanks!

1 Like

Great to hear it!

By the way, I find myself doing similar things with Vectors often enough that I wrote some simple extension methods that let you quickly get a Vector3 that is the same as some other Vector3, but with one dimension that is different:

        public static Vector3 WithX(this Vector3 vector, float x) {
            return new Vector3(x, vector.y, vector.z);
        }

        public static Vector3 WithY(this Vector3 vector, float y) {
            return new Vector3(vector.x, y, vector.z);
        }

        public static Vector3 WithZ(this Vector3 vector, float z) {
            return new Vector3(vector.x, vector.y, z);
        }

With these extensions your code could be a little simpler:transform.position = transform.position.WithX(Random.Range(-11, 12));

sorry me dont do that big boi stuff im too new i just yeeted from scratch lol But thanks for the suggestion!

I’m here because I need to know the position of a different GameObject through the script of a certain one. Example:

I want to access the camera’s coordinates through a script on a cube.

What built-in variable accesses that?

im yeeted from scratch too lol (moving on to roblox or unity… im picking)

Please stop necroing old posts. Create your own thread, ask your own question there.

Thanks.

1 Like