- Home /
Enable script-Component by string?
Hello,
On all my playable gameObjects (Tank, Car, Boat) that are prefabs I have an unique script for its control:
Prefab----Controlscript
Tank - Tank.cs
Car - Car.cs
Boat - Boat.cs
On all these prefabs the control script is disabled to prevent unneccessary calculations when placing it on the leveleditor.
When the level is played, then the control-script should be enabled by a script called Spawner.cs that instantiates the objects from the saved positions.
However, when different vehicles were placed, the instantiated objects have not the same control scripts.
GameObject entityClone = Instantiate(entity,transform.position,transform.rotation) as GameObject;
entityClone.GetComponent(entityClone.name).enabled = true;
But I get an error: Type UnityEngine.Component does not contain a definition for enabled and no extension method enabled' of type UnityEngine.Component could be found (are you missing a using directive or an assembly reference?)
Answer by Bunny83 · Mar 25, 2016 at 02:04 PM
Components can't be enabled / diabled. Behaviours can. MonoBehaviour is derived from Behaviour and Behaviour is derived from Component. So you have to cast the return type of GetComponent to at least Behaviour but in most cases you would simply use MonoBehaviour:
MonoBehaviour script = (MonoBehaviour)entityClone.GetComponent(entityClone.name);
script.enabled = true;
Your answer
Follow this Question
Related Questions
Cannot find a script compnent with raycast 2 Answers
Get Script from every gameobject in a list 1 Answer
Has my project's data corrupted? Script keeps returning null but 20 minutes ago it wasn't? 1 Answer
problem with a list that has to store different things for multiple gameobjects 1 Answer
Identify and Use Unknown Types 1 Answer