[英]How do I enable and disable multiple game objects in Unity?
我需要使用 C# 在 Unity 中启用和禁用包含相同标签的多个游戏对象。谢谢
您可以使用GameObject.FindGameObjectsWithTag()返回具有给定标签的所有游戏对象的数组,然后使用GameObject.SetActive()启用或禁用它们。 就像是:
string tag = ""; // your tag
GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tag);
foreach (GameObject tagged in taggedObjects){
tagged.Setactive(false); // or true
}
不幸的是 GameObject.FindGameObjectsWithTag() 不返回不活动的游戏对象。 因此,您可以在场景开始之前让所有对象保持活动状态,然后在 awake() 或 start() 中重新关闭它们。
Unity 2020 也将具有查找非活动游戏对象的功能。
以上答案弄乱了我的相机或类似的东西。 因此,我根据答案编写了自己的代码。(在下面插入)(张贴以供将来使用)感谢所有回答的人。
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class GameManager : MonoBehaviour
{
public float restarttimer = 3f;
public GameObject Ninja;
public GameObject Covid;
public GameObject[] Buttons;
public GameObject[] Ground;
public GameObject[] HP;
public GameObject[] panelgo;
void Start()
{
//Ninja
Debug.Log("Generating Hero");
Ninja.SetActive(true);
//enemy
Debug.Log("Generating Enemy");
Covid.SetActive(true);
//ground
Debug.Log("Generating Ground");
foreach (GameObject tagged in Ground)
{
tagged.SetActive(true); // or true
}
//HP
foreach (GameObject tagged in HP)
{
tagged.SetActive(true); // or true
}
//Buttons
foreach (GameObject tagged in Buttons)
{
tagged.SetActive(true); // or true
}
//GameOver
foreach (GameObject tagged in panelgo)
{
tagged.SetActive(false); // or true
}
}
public void GameOver()
{
Ninja.SetActive(false);
Covid.SetActive(false);
foreach (GameObject tagged in Ground)
{
tagged.SetActive(false); // or true
}
foreach (GameObject tagged in HP)
{
tagged.SetActive(false); // or true
}
foreach (GameObject tagged in Buttons)
{
tagged.SetActive(false); // or true
}
foreach (GameObject tagged in panelgo)
{
tagged.SetActive(true); // or true
}
}
public void buttonrestart()
{
Invoke("restart", restarttimer);
}
public void restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
PS COVID 敌人的有趣名称;)--------------------线程已关闭-------------------- ------
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.