- Home /
Spawn meshes to scene via dropdown UI button
Hello. I am a new programmer and i want your help. I am working a project where i try to select and spawn a primitive mesh in scene via a dropdown button. I never use something like that so if anyone can help me. I have made an array wich i include my primitives meshes and i want to select them when i select the dropdown options. Here is my code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class ChangeMeshFilter : MonoBehaviour { public Mesh[] myMesh= new Mesh[5]; private int a = 0; private GameObject gObject; public Dropdown MeshSelector;
void Start ()
{
CreateObject();
}
void CreateObject() {
gObject = new GameObject();
gObject.AddComponent<MeshFilter>().mesh = myMesh[0] ;
gObject.AddComponent<MeshRenderer>();
gObject.GetComponent<MeshRenderer>().material.color = Color.green;
}
public void Changer()
{
if (a < 4)
{
a = a + 1;
}
else
{
a = 0;
}
gObject.GetComponent<MeshFilter>().mesh = myMesh[a];
}
Answer by Hellium · May 18, 2021 at 10:58 AM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangeMeshFilter : MonoBehaviour
{
public Mesh[] myMesh= new Mesh[5];
private GameObject gObject;
public Dropdown MeshSelector;
void Start ()
{
CreateObject();
MeshSelector.onValueChanged.AddListener(SelectMesh);
}
void CreateObject() {
gObject = new GameObject();
gObject.AddComponent<MeshFilter>().mesh = myMesh[0] ;
gObject.AddComponent<MeshRenderer>();
gObject.GetComponent<MeshRenderer>().material.color = Color.green;
}
private void SelectMesh(int index)
{
gObject.GetComponent<MeshFilter>().mesh = myMesh[index];
}
Hi and thanks for you time. So if i understand right i must use this script to my script? Or i must you 2 different scripts
The script I've provided is meant to replace yours.
You are the best my friend. Really thanks you. A last question. If i want to select the type of the mesh with the dropdown button, but i want to span this mesh on screen with an other one? is it possible?
Thanks for your time again
Answer by Adil_Alhilali · May 18, 2021 at 11:02 AM
Hi,
Could you please clarify if you want to have an inspector attribute with a dropdown via which you select the type of mesh you want to spawn in your scene or you wan this function to be during run-time in UI?
if you want to make this in the inspector then do this
enum DDLEnum
{
Item1,
Item2,
Item3
};
var dropDown = DDLEnum.Item1;
Hello and thanks for your time. I would like to make it work in runtime