- Home /
Activate and deactivate some script when i press a Key.
Hi to all, I tried to do this script for acrivare and deactivate some script when i press the key B, but how i can assing the specific script? with public var?
#pragma strict
var script : thescript1;
var script : thescript2;
var script : thescript3;
var script : thescript4;
function Start () {
script = GetComponent(thescript1);
script = GetComponent(thescript2);
script = GetComponent(thescript3);
script = GetComponent(thescript4);
script.enabled = false;
}
function Update () {
if (Input.GetKeyDown (KeyCode.B))
script.enabled = true;
else if (Input.GetKeyDown (KeyCode.B))
script.enabled = false;
}
Answer by OrbitSoft · Feb 27, 2014 at 05:50 PM
An efficient way of doing this could be:
var myScripts1 : MonoBehaviour[]; // Scripts to enable
var myScripts2 : MonoBehaviour[]; // " " to disable
void Update()
{
if (Input.GetKeyDown (KeyCode.B))
{
for (i:int=0;i<myScripts1.Length;i++)
{
myScripts1[i].enabled = true;
}
} else if (Input.GetKeyUp(KeyCode.B))
{
for (i:int=0; i<myScripts2.Length;i++)
{
myScripts2[i].enabled = false;
}
}
}
To assign the scripts in the inspector, first attach some script to other gameObjects, then use this script in an empty gameObject, in the inspector set the number of scripts for each array and just drag a gameObject from hierarchy with a script attached.
ther's an error: Unexpected symbol `:' in class, struct, or interface member declaration
Fixed it:
var myScripts1 : $$anonymous$$onoBehaviour[]; // Scripts to enable
var myScripts2 : $$anonymous$$onoBehaviour[]; // " " to disable
function Update()
{
if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.B))
{
for (var i:int=0;i<myScripts1.Length;i++)
{
myScripts1[i].enabled = true;
}
} else if (Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.B))
{
for (var b:int=0; b<myScripts2.Length;b++)
{
myScripts2[b].enabled = false;
}
}
}
it dosn't work :( i created 2 empty gameobect with the active/deactive scripts, and i drag they into inspector (myscript1, and myscript2), but in play mode these two script are enabled. i tried aldo to add:
function Start ()
{
myScripts1.enabled = false;
myScripts2.enabled = false;
}
But is an error.
Answer by RudyTheDev · Feb 27, 2014 at 05:51 PM
In JavaScript var
s are public
by default. First, you need to name all your variables differently (script1, script2, myScript, someOtherScript...) Then drag&drop your GameObjects with those scripts attached to the script fields in inspector of your main GameObject. Then enable/disable whichever you need.