- Home /
How to activate a gameobject via scripting ???
In my game I need to deactivate a gameobject when I click it occurs and make it activated in all other time.I use the following code.
public GameObject me;
void Update ()
{
me.active = true;
}
void OnMouseDown()
{
me.active = false;
}
I am attaching this script to the gameobject which must be deactivated.But I am able to deactivate when I click it but it is not at all re-activating. Is there anything I have missed out?? I have also used gameobject.active,gameobject.SetActive().Nothing worked.
I'm confused about what you are trying to do here. First I assume that 'me' is assigned the same game object this script is attached to? Note 'if' this worked, then your object would only be deactivated for the remainder of the frame. On the next frame it would again be active. Is that really want you want to attempt to do? If that's really want you want, then @hexer's approach will work:
void Update ()
{
renderer.enabled = true;
collider.enabled = true; // Assu$$anonymous$$g there is a collider
}
void On$$anonymous$$ouseDown()
{
renderer.enabled = false;
collider.enabled = false; // Assu$$anonymous$$g there is a collider
}
If you enable renderer and collider components in the update function again, object will self-enable those components the following frame.
Answer by KillMobil · Apr 28, 2014 at 01:13 PM
after the object has been deactivated the Update () function does not get called any more.
the handling of the reactivation will need to be handled be another object that preferable handles most of the proccess.
Answer by Hexer · Apr 28, 2014 at 02:25 PM
Instead of de-activate the object, you want to de-activate just something like the collider and/or the rendering. Try something like this.
void OnMouseDown()
{
GameObject.GetComponent(SpriteRenderer).enabled=false;
}
This lets you disable the rendering of the object.(Instead of disabling the whole object) This code might not work because I mainly use UnityScript but hopefully this can help you out abit
Doesn't Void Update() repeat the command each second? it means that, when deactivating. The object will immediatly be enabled again.
I guess this can be solved by using if statements.
I would be:
void On$$anonymous$$ouseDown() {
bool isEnabled = gameObject.GetComponent<Renderer>().enabled;
gameObject.GetComponent<Renderer>().enabled = !isEnabled;
}
If you set the collider component to false, then the object will never get the On$$anonymous$$ouseDown event again (unless being enabled from another source).
Your answer
Follow this Question
Related Questions
How to activate/deactivate a component(Animator) when a specific game object was activated 0 Answers
Activate Game object when in Camera view and deactivate when out of camera view. 2 Answers
ReActivate object with null movement ?? 2 Answers
Activating/Deactivating GameObject Problem :( 3 Answers
Cannot deactivate / activate gameobject, even in editor! 6 Answers