- Home /
How do I deactivate an object from a script that is attached to him,How do I deactivate an object if I dont have gameobject to work with
I write a script that generates 100 bricks(10x10), like a floor inside a room made of bricks. After 10 seconds the bricks from certain columns I want to deactivate. What do I write inside the brick script do deactivate itself when certain time has passed. I cant create a script somewhere else and drag/drop each object because when I stop the code the bricks doesn't exist. They are generated when I hit play
Answer by rh_galaxy · Sep 21, 2020 at 10:45 PM
Can't you have the activation/deactivation of bricks done in the script that generates the bricks? Just keep the game objects in the script.
float timer = 0;
GameObject[] bricks;
Start()
{
//generate bricks 10x10
for(int i=0; i<100; i++) brick[i] = Instantiate(...);
}
Update()
{
timer += Time.DeltaTime;
//deactivate a brick after a time
if(timer>10.0f) brick[22].SetActive(false);
}
Answer by CodesCove · Sep 21, 2020 at 11:04 PM
If you want to attach the timer script to the actual gameobject then you can do a component like this:
public class DisableTimer: MonoBehaviour
{
public float disableDelay = 10;
public void OnEnable()
{
Invoke("Disable", disableDelay);
}
public void Disable()
{
this.gameObject.SetActive(false);
}
}
Just attach that to the brick and when enabled it will disable the gameobject it is attached to after disableDelay seconds..
Notice that this is not very generic way to do this kind of control.. but should work for your case based on your description.
Your answer
![](https://koobas.hobune.stream/wayback/20220613012152im_/https://answers.unity.com/themes/thub/images/avi.jpg)