- Home /
Do something if position Y is 4. (C#)
l have a script that enables useGravity on trigger enter, which works fine. But l want it to disable useGravity if transform.position.y is 4.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gravity : MonoBehaviour {
private void Update()
{
if (transform.position == new Vector3(transform.position.x, 4, transform.position.z))
{
GetComponent<Rigidbody>().useGravity = false;
Debug.Log("Gravitation Disabled");
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.name == "enGrav")
{
GetComponent<Rigidbody>().useGravity = true;
Debug.Log("Gravitation Enabled");
}
}
}
But it didn't work, and l have no clue why.
Answer by wornTunic · Sep 26, 2017 at 01:41 PM
@MasterN1 First off, those Vector3-s won't be the same since they are two different objects, so you're comparing more than only x, y and z values. So, you should go with:
if (transform.position.y == 4){
GetComponent<Rigidbody>().useGravity = false;
Debug.Log("Gravitation Disabled");
}
Second, since Vector3 values are floats, getting the value to be exactly 4 is really a long shot, so you can do something like:
if (transform.position.y > 3.9f && transform.position.y < 4.1f) {
GetComponent<Rigidbody>().useGravity = false;
Debug.Log("Gravitation Disabled");
}
And third, just to make it easier to work with, you can define some offset for that, like this:
public float offset = 0.1f;
And use it:
if (transform.position.y > (4 - offset) && transform.position.y < (4 + offset) ) {
GetComponent<Rigidbody>().useGravity = false;
Debug.Log("Gravitation Disabled");
}
The first point you make is not entirely accurate, though the sentiment is right. Actually I didn't know either that == between Vector3s has a built in tolerance o.O
https://docs.unity3d.com/ScriptReference/Vector3-operator_eq.html
Also worth noting is that when comparing the equality of value types like Vector3, there is a reason why it doesn't make sense to expect reference equality
Answer by Bilelmnasser · Sep 26, 2017 at 01:41 PM
Hello, First if you want to check only the Y value please be simple to do like this
if( transform.position.y == 4.0f)
{
}
sencond , transform.position.y == 4.0f will maybe not be true in any of all your game Frames so it's not accurate to happen as a condition maybe use :
transform.position.y >= 4.0f
Your answer
Follow this Question
Related Questions
Issue using wheelColliders around sphere 1 Answer
Increase speed of an object's fall 1 Answer
Errors with gravity switching... 1 Answer
how to keep a "ship" over a platform or rigidbody? 0 Answers
Gravity and Grounding 2 Answers