从脚本启用/禁用GameObject组件[Unity3D]

问题描述 投票:0回答:2

我需要在一个脚本中设置一个布尔值(放在一个名为“bouclier”的变量中)来启用或禁用GameObject。

变量在游戏对象Player中(右下角):

enter image description here

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

enter image description here

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

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;
        }
    }
}

我必须遗漏一些东西,因为这会出现这个错误消息:

enter image description here

知道如何正确完成这个吗?

c# unity3d
2个回答
4
投票

使用GameObject.SetActive()函数激活或停用GameObject,如下所示:

Bouclier.SetActive(false);

我认为GameObject.enabled是旧的统一API。此外,如果您想知道GameObject的当前激活状态,请使用GameObject.activeSelf,它是一个只读变量,如下所示:

Debug.Log(Bouclier.activeSelf);

0
投票

它会起作用

public GameObject otherobj;//your other object
public string scr;// your secound script name
void Start () {
(otherobj. GetComponent(scr) as MonoBehaviour).enabled = false;
}
© www.soinside.com 2019 - 2024. All rights reserved.