Search code examples
c#unity-game-engine

How to refer to a component as something else


I have to type transform.position.x a lot and I'm pretty sure there's a way to shorten it, but I don't remember how.

There's a way to refer to something else that I think is like this transform.position.x > x to make it so when you type x you're referring to transform.position.x. I know you can just make a variable that updates every frame, but I don't want to do that.


Solution

  • I think what you want is a property:

    public class Foo : MonoBehaviour {
        float x => transform.position.x;
    }
    

    Now you can use x within the class Foo. Each time you use it, it gets the current value of transform.position.x.

    You can also implement it for setting the value of transform.position.x:

    public class Foo : MonoBehaviour {
        float x {
            get => transform.position.x;
            set {
                var position = transform.position;
                position.x = value;
                transform.position = position;
            }
        }
    }