Hi
I have a problem with a GameObject dynamically created. When I try to do a raycast to detect him, it doesn’t work.
Here it is the code to create the GameObject :
for (int i =0; i <8; i++)
{
buttons[i] = new GameObject();
buttons[i].AddComponent("MeshFilter");
buttons[i].AddComponent("MeshCollider89");
buttons[i].AddComponent("MeshRenderer");
buttons[i].AddComponent("ButtonBehaviour");
Material newMaterial = Resources.Load("ButtonMaterial1", typeof(Material)) as Material;
buttons[i].renderer.material = newMaterial ;
}
When I add the ButtonBehaviour script, this script extends the script Button, wich creates the geometry of the GameObject
public class Button : MonoBehaviour {
public Texture2D tex;
GameObject button;
// Use this for initialization
void Start () {
MeshFilter mf = GetComponent<MeshFilter> ();
Mesh mesh = new Mesh ();
mf.renderer.enabled = true;
mf.mesh = mesh;
Vector3[] vertices = new Vector3[4]
{
new Vector3 (0, 0, 0),
new Vector3 (2.5f, 0, 0),
new Vector3 (0, 2.5f, 0),
new Vector3 (2.5f, 2.5f, 0)
};
int[] tri = new int [6];
tri [0] = 0;
tri [1] = 2;
tri [2] = 1;
tri [3] = 2;
tri [4] = 3;
tri [5] = 1;
Vector3[] normals = new Vector3[4];
normals [0] = -Vector3.forward;
normals [1] = -Vector3.forward;
normals [2] = -Vector3.forward;
normals [3] = -Vector3.forward;
//UVs
Vector2[] uv = new Vector2[4];
uv [0] = new Vector2 (0, 0);
uv [1] = new Vector2 (1, 0);
uv [2] = new Vector2 (0, 1);
uv [3] = new Vector2 (1, 1);
mesh.vertices = vertices;
mesh.triangles = tri;
mesh.normals = normals;
mesh.uv = uv;
}
}
And here it is the raycast detection
if (Input.GetMouseButtonDown (0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
hit.collider.gameObject.renderer.material.color = Color.black;
if ( hit.collider.gameObject.transform == this.transform)
{
Debug.Log("Raycast worked");
}
}
}
When I create the object via script, do I need to attach something to it to work the Raycast?
Thanks in advance!