- Home /
Enabling multiple Monobehaviour Components in a game object
So, i'm trying to make a Multiplayer Game here with various game objects and scripts in c# for every object on the scene.
=)
Thing is, when i spawn the player controlled objects every player shares control over scripts for each spawned gameObject on the scene, that means, when somebody presses "s" for example, every player moves backwards, and that's not how i want game to behave.
--So, the only way i know to solve this, is by spawning 'em with all their scripts (the components) disabled and enable 'em with another script on the gameobject, but i had to make a script to enable every component one by one, and it got really time comsuning to create or edit a new script every time i add a new one to new units n' so on, so i figured out i could do something like this script below.
(v)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerNetControl : NetworkBehaviour {
public MonoBehaviour[] components2enable;
public override void OnStartLocalPlayer()
{
foreach (MonoBehaviour cmp in components2enable)
{
cmp.enabled = true;
}
}
}
after doing this, i expected every "monobehaviour component" i added to the script using unity, to be enabled when for the player who controlled the game object only, but it does nothing, i check the components on the gameobject testing this out, they are all still disabled.
Also, is there any way for me to solve this problem in any other way than the one i know? if so, i would love you to illuminate me teaching me how.
Please help, i've started coding recently and i really need help with C#
Answer by voncarp · May 01, 2018 at 02:52 AM
I would suggest turning on all the scripts and just disabling them if they are not the local player:
using UnityEngine;
using UnityEngine.Networking;
public class PlayerNetControl : NetworkBehaviour {
void Start() {
if (!isLocalPlayer) {
this.enabled = false;
}
}
}
Your answer
Follow this Question
Related Questions
[C#] Quaternion Rotations with Input.GetAxis problems. 1 Answer
How do you check if a game object is set active using an if statement? 2 Answers
"Follow Target" script with a prefab (C#) Help me please! 1 Answer
Problems with Gyroscope VR Car Game 0 Answers
Cannot destroy Component while GameObject is being activated or deactivated 2 Answers