我正在关注关于程序生成网格的教程,我想知道为什么当 List 只有一个 get 访问器时,可以将 .Add() 添加到作为类属性的 List 中。我是 C# 的新手,我在这里缺少什么?
例如,教程让用户编写这个类:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshBuilder
{
private List<Vector3> m_Vertices = new List<Vector3>();
public List<Vector3> Vertices { get { return m_Vertices; } }
private List<Vector3> m_Normals = new List<Vector3>();
public List<Vector3> Normals { get { return m_Normals; } }
private List<Vector2> m_UVs = new List<Vector2>();
public List<Vector2> UVs { get { return m_UVs; } }
private List<int> m_Indices = new List<int>();
public void AddTriangle(int index0, int index1, int index2)
{
m_Indices.Add(index0);
m_Indices.Add(index1);
m_Indices.Add(index2);
}
public Mesh CreateMesh()
{
Mesh mesh = new Mesh();
mesh.vertices = m_Vertices.ToArray();
mesh.triangles = m_Indices.ToArray();
//Normals are optional. Only use them if we have the correct amount:
if (m_Normals.Count == m_Vertices.Count)
mesh.normals = m_Normals.ToArray();
//UVs are optional. Only use them if we have the correct amount:
if (m_UVs.Count == m_Vertices.Count)
mesh.uv = m_UVs.ToArray();
mesh.RecalculateBounds();
return mesh;
}
}
然后我们编写另一个使用该类的脚本:
using UnityEngine;
using System.Collections;
public class ProcQuad : MonoBehaviour {
float m_Width = 1;
float m_Length = 1;
// Use this for initialization
void Start () {
MeshBuilder meshBuilder = new MeshBuilder();
//set up vertices and triangles
meshBuilder.Vertices.Add (new Vector3(0.0f, 0.0f, 0.0f));
meshBuilder.UVs.Add(new Vector2(0.0f, 0.0f));
meshBuilder.Normals.Add(Vector3.up);
meshBuilder.Vertices.Add(new Vector3(0.0f, 0.0f, m_Length));
meshBuilder.UVs.Add(new Vector2(0.0f, 1.0f));
meshBuilder.Normals.Add (Vector3.up);
meshBuilder.Vertices.Add(new Vector3(m_Width, 0.0f, m_Length));
meshBuilder.UVs.Add(new Vector2(1.0f, 1.0f));
meshBuilder.Normals.Add(Vector3.up);
meshBuilder.Vertices.Add (new Vector3(m_Width, 0.0f, 0.0f));
meshBuilder.UVs.Add(new Vector2(1.0f, 0.0f));
meshBuilder.Normals.Add(Vector3.up);
meshBuilder.AddTriangle(0, 1, 2);
meshBuilder.AddTriangle(0, 2, 3);
MeshFilter filter = GetComponent<MeshFilter>();
if (filter != null)
{
filter.sharedMesh = meshBuilder.CreateMesh();
}
}
// Update is called once per frame
void Update () {
}
}
那么为什么我们能够执行:
meshBuilder.Vertices.Add (new Vector3(0.0f, 0.0f, 0.0f));
当属性 Vertices 只有一个 get 访问器时,为什么它会修改私有字段 m_Vertices?
public List<Vector3> Vertices { get { return m_Vertices; } }
感谢您的洞察力。
如果有人对本教程感兴趣,我在这里找到了它: