LoginSignup
1
0

UnityのVector3もどきを作ってみたかったので作った!

Posted at

目的

C#言語への理解がまだ未熟のため実際に使ってこなかった構造体を使って理解を深める

想定する出力結果

1,2,3
0,0,0
  • 1行目は各軸の成分に任意の値を代入して出力した値
  • 2行目はゼロベクトルの値を構造体から参照して出力した値
  • 各軸の成分は","区切りで出力して改行。

実際に想定通りに機能したコード

using System;
namespace Struct_Test
{
    public struct Vector3
    {
        /*各軸の成分*/
        public float x, y, z;
        /*読み取り専用のVector3型のプロパティ。ここではVector3.zero*/
        public static Vector3 zero
        {
            get { return new Vector3(0,0,0); }
        }
        /*構造体のコンストラクター*/
        public Vector3(float x, float y, float z)
        {
            this.x = x; this.y = y; this.z = z;
        }
        /*構造体のデータをstring型で表示する際、これがないとnamespace.thisの文字列しか出力されないのでカスタムの文字列で出力。*/
        public new string ToString() => $"{x},{y},{z}";
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Vector3 v = new Vector3();
            v.x = 1; v.y = 2; v.z = 3;
            Console.WriteLine(v.ToString());
            Console.WriteLine(Vector3.zero.ToString());
        }
    }
}

コードを書いている途中で当たった問題...

  • 循環参照
    ↑これに引っかかってしまった。実際に引っかかる原因になったコードが
    public Vector3 zero = new Vector3(0,0,0);
    これでは循環参照が発生するらしく、調べてみた結果
public static Vector3 zero
{
       get { return new Vector3(0,0,0); }
}

これが正解みたいだ。
つぎに","区切りでstring型で出力するためのメソッド
public new string ToString() => $"{x},{y},{z}";
を追加して、完成!

今回得たもの

  • 構造体に対する理解を少々
  • get,setの使い方への理解少々

まとめ

構造体とプロパティはおもしろい

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0