如何禁用盒子碰撞器和改变多个对象的材质与一个输入(Unity)



我想改变材质,并在按下一个键或接收单个输入时禁用具有相同标签的多个对象的框碰撞器,假设这发生在点击"w"键盘上的键

我最初的想法是循环遍历所有对象与标签和禁用它并改变材料。但我就是做不到。(我是c#新手)

你应该尽可能少地使用FindGameObjectsWithTag()或根本不使用(因为它非常昂贵),而不是在运行时不需要查找GameObjects,使用像List这样的数据结构预先保存所有GameObjects。

如果你需要找到GameObjects.

  • 首先检查Update()方法内所需的输入
  • 然后在里面你可以得到所有的GameObjects使用FindGameObjectWithTag()回调并将其保存到数组之后,我们可以循环遍历数组并获得collider渲染器随附最后我们禁用碰撞器渲染器的材质我们应该使用bool所以我们的输入不应该在所有collider之前被计数材料和改变了

代码如下:

public class TestFind : MonoBehaviour
{
public Material newMaterial;

private bool _haveAllObjectsFound = false;

private void Update()
{
// check if the W key is pressed and we haven't found all the objects yet
if (Input.GetKeyDown(KeyCode.W) && !_haveAllObjectsFound)
{
// gets all the game object with the tag "MyTag"
GameObject[] allFoundObjects = GameObject.FindGameObjectsWithTag("MyTag");
_haveAllObjectsFound = true;
// loop through all the found objects to disable their colliders and change their materials
foreach (var foundObject in allFoundObjects)
{
BoxCollider foundCollider = foundObject.GetComponent<BoxCollider>();
Renderer foundRenderer = foundObject.GetComponent<Renderer>();

foundCollider.enabled = false;
foundRenderer.material = newMaterial;
}

_haveAllObjectsFound = false;
}
}
}

如果你不需要找到GameObjects在运行时. .

  • 使用List存储和设置GameObjects到编辑器/检查器
  • 中的列表
  • 现在直接循环遍历List而不是找到并获得GameObjects通过标记

代码如下:

public class TestFind : MonoBehaviour
{
public List<GameObject> allFoundObjects = new List<GameObject>();
public Material newMaterial;

private bool _haveAllObjectsFound = false;

private void Update()
{
// check if the W key is pressed and we haven't found all the objects yet
if (Input.GetKeyDown(KeyCode.W) && !_haveAllObjectsFound)
{
_haveAllObjectsFound = true;
// loop through all the found objects to disable their colliders and change their materials
foreach (var foundObject in allFoundObjects)
{
BoxCollider foundCollider = foundObject.GetComponent<BoxCollider>();
Renderer foundRenderer = foundObject.GetComponent<Renderer>();

foundCollider.enabled = false;
foundRenderer.material = newMaterial;
}

_haveAllObjectsFound = false;
}
}
}

相关内容

  • 没有找到相关文章

最新更新