- Home /
How to Instantiate a prefab on the surface of a curved structure or mesh
I'm making a game where a ball is rolling along a curved surface, like a 'u' shape or a halfpipe. I want to instantiate a "Hole" prefab that the ball can fall into on the surface of the structure. How would I make the holes instantiate at a random point on the structure or mesh? I was thinking about using raycasting, but I'm not very good at that. Any ideas?
Answer by Glurth · Feb 17, 2015 at 02:30 AM
You could select a random vertex from the mesh's vertex array (an array of 3d points)
int index=Random.Range(0,mesh.vertices.count);
Vector3 someRandomlySelectedVertexPosition= mesh.vertices[index];
http://docs.unity3d.com/ScriptReference/Mesh.html
These vector3's are in local space,so you may need to transform them to world space, depending on how you child your instantiated object.
Vector3 instancePos=transform.TransformPoint(someRandomlySelectedVertexPosition);
http://docs.unity3d.com/ScriptReference/Transform.TransformPoint.html
Then instantiate
Instantiate(pitPrefab, instancePos, mesh.normal[index]); //hmm for rotation, you could probably use the meshs normal for that vertex! try it? edit: I think this would need to be transformed too, at least it's orientation.
http://docs.unity3d.com/ScriptReference/Object.Instantiate.html
I changed the code to the following since mesh.verticies.count was not valid according to the console
public $$anonymous$$esh mesh;
float index = Random.Range (0, mesh.vertices.Length);
Vector3 someRandomlySelectedVertexPosition = mesh.vertices[index];
and now I'm getting the following error on the line with the vector 3:
error CS0266: Cannot implicitly convert type `float' to `int'. An explicit conversion exists (are you missing a cast?)
Also, it says that "normal" does not exist under the $$anonymous$$esh class.
good fix regarding my using "count" error.
Take a look at that first link I posted to find the correct name of the normals array (might need to scroll down a bit). Those Doc's will be your best friend when program$$anonymous$$g unity. Or maybe START with Quaternion.Identity(no rotation) for the orientation, til you get the placement working, THEN look at setting the orientation.
Random range return a float type number, to convert it to an int (whole numbers) you need to "cast it" with (int). This will "chop off" any fractions.
int index= (int)Random.Range(...);
You can only use int type numbers to index into an array, which is the cause of your error CS0266.
For anyone else wondering, the correct variable is mesh.vertexCount to get the count of vertices in the mesh.