如何在Unity C#中仅使用脚本中的游戏对象启用零件/组件

我正在使用Photon在我的游戏中制作多人游戏,以确保一个玩家无法控制它们,当你产生时,客户端它会激活你的脚本/相机,这样你就可以看到并移动。

虽然我想不出解决这个问题的办法,因为我不知道如何启用/禁用儿童的组件或启用孩子的孩子。

我想通过脚本http://imgur.com/ZntA8Qx启用它

这个http://imgur.com/Nd0Ktoy

我的脚本是这样的:

using UnityEngine; using System.Collections; public class NetworkManager : MonoBehaviour { public Camera standByCamera; // Use this for initialization void Start () { Connect(); } void Connect() { Debug.Log("Attempting to connect to Master..."); PhotonNetwork.ConnectUsingSettings("0.0.1"); } void OnGUI() { GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString()); } void OnConnectedToMaster() { Debug.Log("Joined Master Successfully."); Debug.Log("Attempting to connect to a random room..."); PhotonNetwork.JoinRandomRoom(); } void OnPhotonRandomJoinFailed(){ Debug.Log("Join Failed: No Rooms."); Debug.Log("Creating Room..."); PhotonNetwork.CreateRoom(null); } void OnJoinedRoom() { Debug.Log("Joined Successfully."); SpawnMyPlayer(); } void SpawnMyPlayer() { GameObject myPlayerGO = (GameObject)PhotonNetwork.Instantiate("Body", Vector3.zero, Quaternion.identity, 0); standByCamera.enabled = false; ((MonoBehaviour)myPlayerGO.GetComponent("Movement")).enabled = true; } } 

在monobehaivour下面底部的位是我想要启用它们的位置正如你所看到的,我已经想出如何激活我生成的游戏对象的一部分,我只需要帮助我上面所说的,谢谢您的帮助。

我正在通过预制件生成它,所以我希望它只编辑我生成的那个,而不是编辑级别中的每一个,就像我想使用myPlayerGO Game对象启用这些组件一样。

这就是我需要让我的游戏工作的所有内容,所以请帮忙。

如果这是重复的,我很抱歉,因为我不确定如何说出这个标题。

我统一你可以使用gameObject.GetComponentInChildren启用和禁用子对象中的组件

 ComponentYouNeed component = gameObject.GetComponentInChildren(); component.enabled = false; 

也可以使用gameObject.GetComponentsInChildren

两个图像链接都去了同一个地方,但我想我明白了。

我可能会建议你放置一些脚本,允许你在Body游戏对象中连接HeadMovement脚本。 例如:

 public class BodyController : MonoBehaviour { public HeadMovement headMovement; } 

然后你可以在你的预制件中连接它,然后打电话:

 BodyController bc = myPlayerGo.GetComponent(); bc.headMovement.enabled = true; 

另一种解决方法是使用GetComponentsInChildren():

 HeadMovement hm = myPlayerGo.GetComponentsInChildren(true)[0]; //the true is important because it will find disabled components. hm.enabled = true; 

我可能会说第一个是更好的选择,因为它更明确,也更快。 如果您有多个HeadMovements,那么您将遇到问题。 它还需要抓取整个预制层次结构,以便在编译时找到您已经知道位置的内容。