Gameobject follow individual vertex movement

Hi,

Given any 3D model, I’m trying to get the position of all vertices that it has and instantiate a sphere primitive at runtime. I was able to get the initial position of the vertex point correct but when I try to rotate the model I can’t seem to update the position of the sphere markers. Please see my code below:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class VertexPointHandler : MonoBehaviour {
    private Mesh mesh;
    private Vector3[] vertices;

    public float speed = 5.0f;

    private List<GameObject> markerList = new List<GameObject>();

    public GameObject marker;

    // Use this for initialization
    void Start () {
        mesh = GetComponent<MeshFilter>().mesh;
        vertices = mesh.vertices;

        foreach (Vector3 v in vertices)
        {
                Instantiate(marker);
                Vector3 worldPt = transform.TransformPoint(v);
                marker.transform.position = worldPt;
                markerList.Add(marker);
        }
    }

    // Update is called once per frame
    void Update()
    {
        transform.Rotate(new Vector3(0, speed * Time.deltaTime, 0));
        mesh.RecalculateBounds();

        Vector3[] vertices_update = mesh.vertices;

        for (int i=0; i< vertices_update.Length; i++)
        {
            Vector3 worldPt = transform.TransformPoint(vertices_update[i]);
            markerList[i].transform.position = transform.position + worldPt;
            //markerList[i].transform.position = transform.position + vertices[i];
        }
    }
}

Start:
2545687--176921--upload_2016-3-9_17-15-33.png

After cube rotation:
2545687--176922--upload_2016-3-9_17-16-44.png

Thanks everyone!

Here is a hint about what’s going wrong:

What’s going on at lines 23, 25 and 26?

You should name the variable “marker” to something like “markerPrefab”. It helps to avoid this kind of mistakes.

Also you don’t need to recalculate the mesh bounds for what you want to do.

Not related to your problem but more an optimization:
Note that Mesh.vertices returns a copy of the array of vertices, which means an array is created on each update. It would be best to cache this array on Start or Awake.

Hi erlcbegue,

noted on improving naming conventions and the optimization tip at the end.

any idea how to track movement of each individual vertex so the sphere marker can be updated as well?

Thanks!