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

标签 c# unity3d

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

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

enter image description here

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

enter image description here

为此,我将脚本附加到游戏对象“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;
        }
    }
}

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

enter image description here

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

最佳答案

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

Bouclier.SetActive(false);

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

关于c# - 从脚本启用/禁用游戏对象组件 [Unity3D],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238795/

相关文章:

c# - 如何更改 Pane 上图形之间的距离?

c# - 为什么此加密的字符串中包含有趣的字符?不可读吗?

c# - Xml 序列化在简单类上因 NullReferenceException 而失败

c# - 智能感知不再有效

c# - 在 Unity 中找不到 rigidBody2D.MovePosition

user-interface - 某些 Windows 8 和 8.1 上的 Unity3d 4.6 UI 图像错误

c# - 获取数组的长度

c# - C# 扩展方法中的泛型约束

c# - UWP:从自定义 .resw 文件中读取所有条目

c# - 关于实例化抽象类的子类的疑问