2

такая проблема: есть несколько кнопок созданные с помощью скрипта, мне нужно сделать так, что бы после нажатия кнопка присваивала определенное значение X и Y и удалялась. Как присвоить я знаю, а вот как удалить определенную кнопку, на которую кликнул - нет.

введите сюда описание изображения

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;


public class NewBehaviourScript : MonoBehaviour
{
    public Transform panel;

    public Font font;
    public Text x;
    public Text y;
    int chislo = 0;
    int chislo2 = 0;

    private void FixedUpdate()
    {
        x.text = string.Format("X= {0}", chislo);
        y.text = string.Format("Y= {0}", chislo2);
    }

    public void createButton()
    {
        int Number = UnityEngine.Random.Range(1, 50);
        int Number2 = UnityEngine.Random.Range(1, 50);
        GameObject newButton = new GameObject("knopka" + Number, typeof(Image), typeof(Button), typeof(LayoutElement));
        newButton.transform.SetParent(panel);

        newButton.GetComponent<Image>().color = new Color(0, 1, 0, 1);

        newButton.transform.SetParent(newButton.transform);

        newButton.GetComponent<Button>().onClick.AddListener(() => ButtonClicked(Number, Number2));


        GameObject newText = new GameObject("New text X" + Number, typeof(Text));
        newText.transform.SetParent(newButton.transform);    
        RectTransform rt = newText.GetComponent<RectTransform>();
        rt.localPosition = new Vector2(-54, 0);
        rt.anchorMin = new Vector2(0.5F, 0);
        rt.anchorMax = new Vector2(1, 1);    
        rt.anchoredPosition = new Vector2(-100, 0);
        rt.sizeDelta = new Vector2(-7.6294e-06F, 0);
        newText.GetComponent<Text>().color = new Color(0, 0, 0);
        newText.GetComponent<Text>().alignment = TextAnchor.MiddleCenter;
        newText.GetComponent<Text>().text = Convert.ToString(Number);
        newText.GetComponent<Text>().font = font;
        newText.GetComponent<Text>().fontSize = 50;


        GameObject newText1 = new GameObject("New text Y" + Number2, typeof(Text));
        newText1.transform.SetParent(newButton.transform);      
        RectTransform ret = newText1.GetComponent<RectTransform>();
        ret.localPosition = new Vector2(-240, 272.65F);
        ret.anchorMin = new Vector2(0.5F, 0.5F);
        ret.anchorMax = new Vector2(0.5F, 0.5F);
        ret.anchoredPosition = new Vector2(50, 0);
        ret.sizeDelta = new Vector2(100, 100);
        newText1.GetComponent<Text>().color = new Color(0, 0, 0);
        newText1.GetComponent<Text>().alignment = TextAnchor.MiddleCenter;
        newText1.GetComponent<Text>().text = Convert.ToString(Number2);
        newText1.GetComponent<Text>().font = font;
        newText1.GetComponent<Text>().fontSize = 50;
    }

    public void ButtonClicked(int x, int y)
    {
        chislo = x;
        chislo2 = y;
    }
}

1 ответ 1

4

Чтобы уничтожить любой GameObject необходимо воспользоваться методом GameObject.Destroy ();

Допустим у нас есть:

GameObject gameObject = ...;

Вызов этого метода с аргументом gameObject вызовет уничтожение этого объекта сцены:

GameObject.Destroy(gameObject);

А вызов его же, с переданной туда ссылкой на компонент, вызовет уничтожение компонента:

GameObject.Destroy(gameObject.getComponent<MyComponent>());

Так же есть возможность отложить удаление на некоторое время:

GameObject.Destroy (gameObject, 1); // тут секунды

PS: GameObject.Destroy можно не писать, если Вы находитесь внутри MonoBehaviour, он получает этот метод транзитивно и можно писать просто:

Destroy(gameObject);
0

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.