Ivan Cortes
Ivan Cortes

Reputation: 35

How can I disable script in runtime?

I have a problem, it is that gameobject.enabled does not work, and I tried everything but I can not solve it, I would appreciate very much if you help me. Here are the scripts I wrote:

enter image description here enter image description here

Beforehand, thank you very much.

Here the code:

public class GenerarCartaAleatoria : MonoBehaviour
{
    public GameObject go, padre;
    
    string numSprite;
    int contador = 1;
    int contadorChild;
    int contadorOrder = 329;

    public void Generar()
    {
        string numRandom = Random.Range(1,36).ToString();
        int numLenght = numRandom.Length;

        if (numLenght == 1)
        {
            numSprite = "Sprites/000" + numRandom;
        }
        else if(numLenght == 2)
        {
            numSprite = "Sprites/00" + numRandom;
        }
        else if (numLenght == 3)
        {
            numSprite = "Sprites/0" + numRandom;
        }
        else if (numLenght == 4)
        {
            numSprite = "Sprites/" + numRandom;
        }

        GameObject spriteCosa = Instantiate(go);

        spriteCosa.transform.parent = padre.transform;

        GameObject cosasa = transform.GetChild(contadorChild).gameObject;

        cosasa.AddComponent<Image>();

        cosasa.GetComponent<GenerarCartaAleatoria>().enabled = false;

        cosasa.transform.SetSiblingIndex(0);
        
        cosasa.name = contador.ToString();

        cosasa.GetComponent<Image>().sprite = Resources.Load<Sprite>(numSprite);

        cosasa.GetComponent<RectTransform>().localScale = new Vector3(1,1,0);

        cosasa.GetComponent<RectTransform>().localPosition = new Vector3(-171, contadorOrder, 0);

        contador++;
        contadorChild++;
        contadorOrder += 100;
    }
}

My hierarchy:

enter image description here

Upvotes: 0

Views: 338

Answers (1)

TEEBQNE
TEEBQNE

Reputation: 6266

If you are trying to disable a GameObject, the use is gameObejct.SetActive(bool) where bool is either true or false. To turn it off, the line would be yourGameObjectHere.SetActive(false) or in your case, cosas.SetActive(false).

I am a bit confused with the wording of your question though. You wrote gameObject.enabled does not work. Do you mean that the .enabled is not working on your component? When you use the .enable it is used on a component-wise basis, so it would be disabling the component called GenerarCartaAleotoria on the gameObject you are finding. Is this .enabled = false not working and that is your question?

Upvotes: 1

Related Questions