I am trying to change the vertex color of an object placed using an instantiation, but I receive an error on the parent object as it has no MeshFilter component.
What I need to do is effect the child objects without checking the parent, to avoid this error.
The code for this is between lines 33 and 46.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ObjectPlacement : MonoBehaviour {
public Text currentPrefab;
protected GameObject instantiated;
Ray ray;
float rayDist;
Vector3 lookPosition;
Plane world = new Plane(Vector3.up, Vector3.zero); //world plane to draw the grid on
Camera cam;
bool isPreview = false;
bool isPlaced = false;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
ray = cam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
world.Raycast(ray, out rayDist);
lookPosition = ray.GetPoint(rayDist);
if(isPreview)
{
Transform[] allChildren = GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren)
{
Debug.Log(allChildren);
Mesh mesh = instantiated.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
Color[] colors = new Color[vertices.Length];
int i = 0;
while (i < vertices.Length)
{
colors[i] = Color.Lerp(Color.green, Color.green, vertices[i].y);
i++;
}
}
}
}
public void selectPrefab(GameObject prefab)
{
if(prefab != null)
{
Vector3 rounedPos = new Vector3(Round(lookPosition.x), 0, Round(lookPosition.z));
Vector2 mouse = Input.mousePosition;
Vector3 finalPosition = lookPosition;
finalPosition.x = GetMultiple(lookPosition.x, 3);
finalPosition.y = GetMultiple(lookPosition.y, 3);
finalPosition.z = GetMultiple(lookPosition.z, 3);
instantiated = Instantiate(prefab, finalPosition, Quaternion.identity) as GameObject;
isPreview = true;
}
}
float Round(float x)
{
return Mathf.Round(x / 3) * 3;
}
int GetMultiple(float x, int multipleOf)
{
return ((int)((x / multipleOf) + 0.5f)) * multipleOf;
}
}