简体   繁体   中英

Unity3D's Vector3 Declaration in C#

I came from c/c++, new in c#.
I think it could be so simple and stupid question for c# programmers.

Anyway, in Unity c#,
What's the difference these two vector3's declarations.


void TestDecl()
{
    //case 1
    Vector3 vectorA = new Vector3(1, 0, 0);

    //case 2
    Vector3 vectorB;
    vectorB.x = 1;

    //it print "1/1"
    Debug.Log(vectorA.x + "/" + vectorB.x);
}


if case 2 is right way to declare vector3 too, I think I don't need to use new operator at all.
It's verbose and not efficient.


Any comments plz.

Well, case 1 will work while case 2 is actually an incomplete initialization. If you declare a struct without initializing it with new, you have to initialize all fields manually or you can't use the struct as a whole. Your case works, because you only use the x component which you have initialized. This however would fail:

Vector3 vectorB;
vectorB.x = 1;
Debug.Log("vectorB: " + vectorB);  // <--CS0165: Use of unassigned local variable

Using an constructor always ensures that all fields are initialized.

Also keep in mind that the fields need to be initialized. If you have private fields and provide properties to access them, you can't initialize them at all except using a constructor.

See this question for reference:
C# Structs: Unassigned local variable?

A major difference is when you start handling common uses of Vector3's within the Unity Engine.

For instance

transform.position.x = 1;

will not work as you cannot modify a value type return value of `UnityEngine.Transform.position'.

transform.position = new Vector3( 1, 0, 0 );

will work however as you're assigning it a new Vector3. This is the same with other transform values so using the 'new' operator is good as it conforms to the standard and is more illustrative of what you're doing.

Using constructors is better practise in the sense that you guarantee access to base elements within the object you are creating. By only initializing particular parts of a class, struct ect, you may cause problems when attempting to use elements that require their own initialization.

By initializing only x in a Vector3, you will encounter this if you attempt to access the z element; "Use of possibly unassigned field `z'"

Summary: Using constructors is better practise as it conforms to the majority of classes and will aid in avoiding null errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM