我有一个Key,用于禁用当前GameObject的MeshRenderer和BoxCollider组件。在禁用这些并且用户再次按下相同的键后,我想再次启用这些相同的组件,但它似乎无法找到这些组件,因为它们被禁用。我怎样才能找到这两个组件并再次启用它们?提前谢谢!
这是我正在使用的脚本的链接(我禁用函数内部第27 + 28行的组件,我试图在函数内部的第36 + 37行再次启用它们):{{3 }}
编辑:或者告诉我我犯了什么错误。
答案 0 :(得分:1)
为什么不迭代所有组件并启用/禁用它?
var allComponents : Component[];
allComponents = gameObject.GetComponents (Component);
for (var component : Component in allComponents) {
// check here if this component is of interest may be by checking
// tag and if it is of interest do the following
//enable disable
component.enabled = !component.enabled;
}
<强> [编辑] 强> 团结v 5.3
public Component[] GetComponentsInChildren(Type t, bool includeInactive = false);
如果includeInactive为true,将返回所有活动和非活动游戏对象。 所以你现在就做以下事情
Component [] compList = yourGameObj.GetComponentsInChildren(typeof(Component));
//or type of game object
foreach(Component comp : compList){
//do your magic
}
<强> [编辑] 强> 我们不是来保姆,我目前没有在我正在使用的PC上安装Unity,但是代码看起来像这样(正确以满足您的需求):
public class Strut : Photon.MonoBehaviour
{
public bool DestroyByRpc;
private MeshRenderer meshRenderer;
private BoxCollider boxCollider;
void Start(){
Component [] compList = yourGameObj.GetComponentsInChildren(typeof(MeshRenderer), true);
if (compList != null && compList.Length > 0)
meshRenderer = compList[0];
compList = yourGameObj.GetComponentsInChildren(typeof(BoxCollider), true);
if (compList != null && compList.Length > 0)
boxCollider = compList[0];
}
void Update()
{
if (Input.GetButtonDown ("LandingStruts")) {
if (this.gameObject.activeSelf == true) {
this.photonView.RPC("HideStrut", PhotonTargets.AllBuffered);
}
else {
this.photonView.RPC("ShowStrut", PhotonTargets.AllBuffered);
}
}
}
[RPC]
public IEnumerator HideStrut()
{
meshRenderer.enabled = false;
boxCollider.enabled = false;
yield return 0;
PhotonNetwork.UnAllocateViewID(this.photonView.viewID);
}
[RPC]
public IEnumerator ShowStrut()
{
meshRenderer.enabled = true;
boxCollider.enabled = true;
yield return 0;
PhotonNetwork.UnAllocateViewID(this.photonView.viewID);
}
}
答案 1 :(得分:1)
您可以在代码中保留组件的引用,因此您无需始终获取它们。 这是一个例子:
public class Strut : Photon.MonoBehaviour
{
MeshRenderer _meshRenderer;
BoxCollider _collider;
void Start()
{
_meshRenderer = GetComponent<MeshRenderer> ();
_collider= GetComponent<BoxCollider> ();
}
[RPC]
public IEnumerator HideStrut()
{
_meshRenderer.enabled = false;
_collider.enabled = false;
yield return 0;
PhotonNetwork.UnAllocateViewID(this.photonView.viewID);
}
[RPC]
public IEnumerator ShowStrut()
{
_meshRenderer.enabled = true;
_collider.enabled = true;
yield return 0;
PhotonNetwork.UnAllocateViewID(this.photonView.viewID);
}