How to Make a Vector Struct and Assign it to Position

Okay, simple question but I can’t really find the answer. I’m making a custom Vector struct for a tutorial series I’m writing, purely for educational purposes. I’m not going to implement all vector2,vector3 methods and properties, but… I’m wondering how do positions get assigned? Is it something in the transform class or the vector structs? The reason I ask is I can’t assign a position to the custom struct without casting it to a vector, which kinda defeats the purpose of making a custom vector struct lol.

So, is there a way to assign a custom vector struct to a position/rotation/scale?

Transform.position is a property of Transform and it’s a Vector3. Nothing you write can change that.

I’m not really understanding the purpose you’re trying to achieve.

Ah, I see. Like I said, it’s for a tutorial series. I figured writing a custom struct would be an easy way to teach the ins and outs of vectors. I guess I’ll just cast it to a vector3.

Depends what exactly you mean by “without casting it to a vector”.

You can implement (explicit, implicit) operators for your custom struct, which can be helpful sometimes.

Here’s an example with implicit operators:

public struct CustomVector3
{
    public float x;
    public float y;
    public float z;

    public static implicit operator Vector3(CustomVector3 v)
    {
        return new Vector3() { x = v.x, y = v.y, z = v.z };
    }

    public static implicit operator CustomVector3(Vector3 v)
    {
        return new CustomVector3() { x = v.x, y = v.y, z = v.z };
    }
}

You can then just assign a CustomVector3 to a Vector3 and vice versa without an explicit cast:

transform.position = new CustomVector3();
3 Likes

Ahh, I was actually talking about the explicit operator, I wasn’t aware of the implicit operator! This is exactly what I wanted, thank you!