描述
在Unity學(xué)習(xí)開(kāi)發(fā)過(guò)程中,會(huì)遇到通過(guò)對(duì)transform.position.x/y/z直接賦值時(shí)報(bào)錯(cuò):

但是
transform.position = Vector3.zero;卻是可以的。
究其原因
查看Transform的腳本你會(huì)發(fā)現(xiàn)position是Vector3類型,并且是一個(gè)自動(dòng)實(shí)現(xiàn)的屬性。
//
// Summary:
// The position of the transform in world space.
public Vector3 position { get; set; }
繼續(xù)查看Vector3的腳本你會(huì)發(fā)現(xiàn)Vector3是struct類型
public struct Vector3
{
public const float kEpsilon = 1E-05F;
//
// Summary:
// X component of the vector.
public float x;
//
// Summary:
// Y component of the vector.
public float y;
//
// Summary:
// Z component of the vector.
public float z;
Vector3是結(jié)構(gòu)體類型,而結(jié)構(gòu)體為值類型,值類型在通過(guò)方法傳遞的時(shí)候,傳遞的只是值的副本。
當(dāng)使用
transform.position.x = 10;
時(shí),這個(gè)position是調(diào)用transform的get方法,得到一個(gè)transform里記錄位置的Vector3私有成員position的臨時(shí)副本,然后再對(duì)這個(gè)副本進(jìn)行修改,所以不會(huì)更改transform中真實(shí)的私有成員position。這樣的修改是毫無(wú)意義的,編譯器會(huì)禁止這樣的修改操作,所以報(bào)錯(cuò)。
但當(dāng)使用
transform.position = Vector3.zero;
時(shí),C#發(fā)現(xiàn)需要對(duì)transform的私有成員進(jìn)行修改,會(huì)自動(dòng)調(diào)用set方法,而這個(gè)set方法是能修改transform的私有成員的。
補(bǔ)充
public Vector3 position { get; set; }
等價(jià)于
private Vector3 mPosition;
public Vector3 position
{
get{
return mPosition;
}
set
{
mPosition = value;
}
}