Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/disable a GameObject component from a script [Unity3D]

Tags:

c#

unity3d

I need to take the value of a boolean (put in a variable called "bouclier") set in one script to enable or disable a GameObject.

The variable is in game object Player (bottom right here):

enter image description here

And I need to enable of disable this game object ("Bouclier01"):

enter image description here

To do this, I attached a script to game object "Bouclier01". Here it is:

using UnityEngine;
using System.Collections;

public class ShowBouclier : MonoBehaviour {

    public GameObject Bouclier01;
    public bool bouclier;

    // Use this for initialization
    void Start () {
        Bouclier01 = Bouclier01.GetComponent<GameObject>();
    }

    // Update is called once per frame
    void Update () {

        Bouclier01.enabled = false;
        if (bouclier == true) {
            Bouclier01.enabled = true;
        }
    }
}

I must be missing something, because this comes up with this error message:

enter image description here

Any idea how to properly accomplish this?

like image 976
Lucien S. Avatar asked Mar 26 '16 17:03

Lucien S.


People also ask

How do I enable and disable GameObject in Unity?

Activate or deactivate the object, where true activates the GameObject and false deactivates the GameObject.


2 Answers

You can use GameObject.SetActive() function to activate or deactivate a GameObject (I think GameObject.enabled was in the old API):

Bouclier.SetActive(false);

By the way, if you want to know the current activation state of a GameObject, use GameObject.activeSelf, which is a read only variable:

Debug.Log(Bouclier.activeSelf);
like image 140
mt3d Avatar answered Nov 14 '22 21:11

mt3d


it will works

public GameObject otherobj;//your other object
public string scr;// your secound script name
void Start () {
(otherobj. GetComponent(scr) as MonoBehaviour).enabled = false;
}
like image 36
Kamran Mohazzab Avatar answered Nov 14 '22 22:11

Kamran Mohazzab