简体   繁体   English

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

[英]Enable/disable a GameObject component from a script [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.我需要取一个脚本中设置的布尔值(放入一个名为“bouclier”的变量中)来启用或禁用游戏对象。

The variable is in game object Player (bottom right here):变量位于游戏对象 Player 中(此处右下角​​):

在此处输入图片说明

And I need to enable of disable this game object ("Bouclier01"):我需要启用或禁用此游戏对象(“Bouclier01”):

在此处输入图片说明

To do this, I attached a script to game object "Bouclier01".为此,我将脚本附加到游戏对象“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:我一定遗漏了一些东西,因为这会出现以下错误消息:

在此处输入图片说明

Any idea how to properly accomplish this?知道如何正确完成此操作吗?

You can use GameObject.SetActive() function to activate or deactivate a GameObject (I think GameObject.enabled was in the old API):您可以使用 GameObject.SetActive() 函数来激活或停用游戏对象(我认为 GameObject.enabled 在旧 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:顺便说一下,如果你想知道一个游戏对象的当前激活状态,可以使用 GameObject.activeSelf,它是一个只读变量:

Debug.Log(Bouclier.activeSelf);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM