I create a SkyMap with a bunch of stars and now I want to instantiate a button with the name of each star by clicking in that specific star. By the moment, everything looks great! I click a star, a button appears with the same name of the star but I want to know now is how I destroy the button of one star when clicking a different star?
In the moment, if i just keep clicking different stars the buttons are going to clone in the same position. Is there a way to call Destroy in this case even though it is the same prefab?
I just want to display the name of the star with a button function as an optional way to see the information of the star, or that is what Im thinking.
I create the buttons like this
Inside a Empty GameObject there is a sphere object with a script called StarSelectDown
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class StarSelectDown : MonoBehaviour
{
public GameObject nameSelected; //this is the button
public void ClickDown()
{
var parentOBj = transform.parent.GetComponent<Transform>(); //this is just taking the name of the empty object that have the star name and see if it shows
Debug.Log(parentOBj.name + parentOBj.position + parentOBj.rotation);
//here is the button
GameObject nameSelec = Instantiate(nameSelected) as GameObject;
nameSelec.transform.SetParent(transform, false);
nameSelec.name = parentOBj.name;
var selectbutton = nameSelec.GetComponentInChildren<Button>();
var selectedText = selectbutton.GetComponentInChildren<Text>();
selectedText.text = parentOBj.name;
}
}
btw, the prefab is displayed with all stars name using a cvs data. So, when running each sphere prefab will have a different star name.
and I use this other code through the camera to click the displayed spheres to instantiate their own button name.
I put this in the camera
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StarSelect : MonoBehaviour
{
[SerializeField]
private LayerMask selectionLayer;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rayHit;
if (Physics.Raycast(ray, out rayHit, Mathf.Infinity, selectionLayer))
{
rayHit.collider.GetComponent<StarSelectDown>().ClickDown();
}
}
}
}
What you want in first part of code, is having UI element, which you can show and hide, rather instantiate and destroy. Then you only need to worry about setting position, name of selected star and other options.