Search Unity

How to Make a Vector Struct and Assign it to Position

Discussion in 'Scripting' started by Mashimaro7, Apr 18, 2021.

  1. Mashimaro7

    Mashimaro7

    Joined:
    Apr 10, 2020
    Posts:
    727
    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?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    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.
     
  3. Mashimaro7

    Mashimaro7

    Joined:
    Apr 10, 2020
    Posts:
    727
    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.
     
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    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:

    Code (CSharp):
    1. public struct CustomVector3
    2. {
    3.     public float x;
    4.     public float y;
    5.     public float z;
    6.  
    7.     public static implicit operator Vector3(CustomVector3 v)
    8.     {
    9.         return new Vector3() { x = v.x, y = v.y, z = v.z };
    10.     }
    11.  
    12.     public static implicit operator CustomVector3(Vector3 v)
    13.     {
    14.         return new CustomVector3() { x = v.x, y = v.y, z = v.z };
    15.     }
    16. }
    You can then just assign a CustomVector3 to a Vector3 and vice versa without an explicit cast:
    Code (CSharp):
    1. transform.position = new CustomVector3();
     
    mopthrow, PraetorBlue and Mashimaro7 like this.
  5. Mashimaro7

    Mashimaro7

    Joined:
    Apr 10, 2020
    Posts:
    727
    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!