代码: - using UnityEngine;
- using System.Collections;
- public class NewBehaviourScript : MonoBehaviour
- {
- public Transform cube1;
- public Transform cube2;
- public Transform a1;
- public Transform a2;
- public Transform a3;
- void Start()
- {
- if (cube1.GetComponent<MeshFilter>().sharedMesh == cube2.GetComponent<MeshFilter>().sharedMesh)
- {
- Debug.LogError("mesh is the same!");
- }
- ChangeCube1Mesh();
- }
- void ChangeCube1Mesh()
- {
- Mesh mesh = cube1.GetComponent<MeshFilter>().mesh; //这里是mesh
- mesh.Clear();
- Vector3 v1 = gameObject.transform.InverseTransformPoint(a1.position);
- Vector3 v2 = gameObject.transform.InverseTransformPoint(a2.position);
- Vector3 v3 = gameObject.transform.InverseTransformPoint(a3.position);
- mesh.vertices = new Vector3[] { v1, v2, v3 };
- mesh.triangles = new int[] { 0, 1, 2 };
- }
- }
复制代码上面如果改变的是cube1的mesh,则效果只是改变cube1的mesh:
如果改为: - void ChangeCube1Mesh()
- {
- Mesh mesh = cube1.GetComponent<MeshFilter>().sharedMesh; //这里是sharedMesh
- mesh.Clear();
- Vector3 v1 = gameObject.transform.InverseTransformPoint(a1.position);
- Vector3 v2 = gameObject.transform.InverseTransformPoint(a2.position);
- Vector3 v3 = gameObject.transform.InverseTransformPoint(a3.position);
- mesh.vertices = new Vector3[] { v1, v2, v3 };
- mesh.triangles = new int[] { 0, 1, 2 };
- }
复制代码可见sharedMesh是公用的,是引用传递。而mesh是值传递,是各自拥有的实例。sharedMesh改变,则所有的使用到此mesh的都改变。
|