How do I enable Parts/Components in Unity C# with only a game object in the script

user4540474 picture user4540474 · Aug 13, 2015 · Viewed 8k times · Source

I am using Photon to make put multiplayer in my game, to ensure that one player doesn't control them all, when you spawn in, client side it will activate your scripts/camera so you can see and move.

Although I can't think of a way around this problem, since I don't know how to enable/disable children's components or enable a child's child.

I want to enable this through scripting http://imgur.com/ZntA8Qx

and this http://imgur.com/Nd0Ktoy

My script is this:

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;

}
}

The bit at the bottom underneath the thing with monobehaivour is where I want to enable them As you can see I have already figured out how to activate something that is part of the game object I spawned, I just need help with what I said above, thank you for your help.

I'm spawning it through a prefab, so I want it to edit only the one I spawn, and not every other one in the level, as in I want to enable these components using the myPlayerGO Game object, and that one only.

This is all I need to get my Game working, so please help.

If this is a duplicate, I'm sorry because I wasn't sure how to word the title of this.

Answer

Nain picture Nain · Aug 13, 2015

I unity you can enable and disable components in child object by using gameObject.GetComponentInChildren

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

Also can use gameObject.GetComponentsInChildren