从脚本启用/禁用游戏对象组件 [Unity3D]

Rod*_*phe 4 c# unity-game-engine

我需要取一个脚本中设置的布尔值(放入一个名为“bouclier”的变量中)来启用或禁用游戏对象。

变量位于游戏对象 Player 中(此处右下角​​):

在此处输入图片说明

我需要启用或禁用此游戏对象(“Bouclier01”):

在此处输入图片说明

为此,我将脚本附加到游戏对象“Bouclier01”。这里是:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我一定遗漏了一些东西,因为这会出现以下错误消息:

在此处输入图片说明

知道如何正确完成此操作吗?

mt3*_*t3d 8

您可以使用 GameObject.SetActive() 函数来激活或停用游戏对象(我认为 GameObject.enabled 在旧 API 中):

Bouclier.SetActive(false);
Run Code Online (Sandbox Code Playgroud)

顺便说一下,如果你想知道游戏对象的当前激活状态,请使用 GameObject.activeSelf,它是一个只读变量:

Debug.Log(Bouclier.activeSelf);
Run Code Online (Sandbox Code Playgroud)