- Home /
Help With Disabling/Enabling single GameObject
Hey, Im using a fairly cludge setup to turn on and off an object with a keypress and I was wondering if someone could help me refine it. Im certain that there are many overlaps with these two scripts that are unnecessary. However whenever I change this setup it never seems to work, I heard that it may have something to do with SetActiveRecursively () But I couldn't get that method to quite work either.
This first script is placed on the object to be toggled disabled/enabled.
function Update () {
if (Input.GetKeyDown("p")) {
gameObject.active = !gameObject.active;
}
}
This script is placed on the first person controller.
var onoff : boolean;
var testObject : GameObject;
function Update () {
if(Input.GetKeyDown("p")){
if (onoff == true)
testObject.active = true;
if (onoff == false)
testObject.active = false;
}
}
Im very new to scripting and they appear to do the same thing, but they do not work without eachother. This is probably due to referencing an object that is disabled and one of the scripts being disabled when toggling. I would really appreciate some help with this matter please.
since they're both using the same key and the same object is the target, why not just get rid of the script you have on the object and only use the one that's on your player?
Unfortunately when I do this the object will only turn on from an off state and will not disable with the second keypress.
Answer by Chimera3D · May 09, 2012 at 06:17 PM
When you disable the object the script doesn't work anymore because the script is disabled to. You need to attach the script to something else.
(edit): Just attach your second script to the fps and make sure you've assigned the variable to the object in the inspector and it should work. No need for the first script. In addition you're not telling the onOff variable to turn on and off, otherwise it's just always false. Try saying if onOff = true, then gameObject.active = false and onOff = false;. Then instead of saying if onOff = false, just say else. Also make a start function and make onOff = true;
I just tried what you recommended and (since the object starts hidden) when I press 'p' the object turns on, but when I press it again it wont turn off?
mix the idea you had from your first script with the 2nd script....
e.g.
var t : GameObject ;
function Update(){
if(getAkey)
t.active = !t.active ;
}
I managed to get it to work by using your suggestions and changing the onOff variables thank you!