- Home /
Make object active and inactive repeatedly in a specific way?
So basically I have this ordinary object (a cube for example) in the scene environment, and I want it to appear for 1 second, and disappear for X amount of seconds (between values 1-30 randomly), and this repeats on its own continuously: (active (1), non-active (9), active (1), non-active (27), active (1)... etc). I have no experience with programming at all really, and it would be so greatly appreciated if i was shown how to do this. Thanks!
IEnumerator StartAction(GameObject target){
while(true){
float seconds = UnityEngine.Random.Range(1,30);
yield return new WaitForSeconds(seconds);
target.SetActive(!target.activeInHierarchy)
}
}
Now call in on of your script like StartCoroutine(StartAction(what is your target)); in where ever you want. if you want to start from the begining call it in start.
Answer by ShadyProductions · Oct 21, 2019 at 08:49 AM
You can achieve this easily by using a coroutine in the update method.
public GameObject obj; // Assign in inspector
private bool hasFaded = false;
public void Update()
{
if (!hasFaded)
{
StartCoroutine(Fade(obj, UnityEngine.Random.Range(1f, 30f)));
}
}
public IEnumerator Fade(GameObject obj, float seconds)
{
hasFaded = true;
obj.SetActive(false);
yield return new WaitForSeconds(seconds);
obj.SetActive(true);
yield return new WaitForSeconds(1f); // Appear for one second
hasFaded = false;
}
Note: Make sure not to map this script on that same object, as when the object is disabled the script will be too, so map this on an empty gameobject or something similar.
Answer by misher · Oct 21, 2019 at 08:56 AM
Create a script and attach it to some object that is always active in the scene.
here is 1 example of how you can achieve what you want with the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Example1 : MonoBehaviour
{
[SerializeField] GameObject target;
[SerializeField] Vector2 hiddenTimeRange = new Vector2(1,30);
[SerializeField] Vector2 shownTimeRange = new Vector2(1, 1);
// Start is called before the first frame update
void Start()
{
StartCoroutine(ShowingAndHiding());
}
IEnumerator ShowingAndHiding()
{
while(true)
{
target.SetActive(true);
float showTime = Random.Range(shownTimeRange.x, shownTimeRange.y);
yield return new WaitForSeconds(showTime);
target.SetActive(false);
float hideTime = Random.Range(hiddenTimeRange.x, hiddenTimeRange.y);
yield return new WaitForSeconds(hideTime);
}
}
}
Don't forget to set the reference to your target object (a cube) in the inspector. You can also change time intervals.
Your answer
![](https://koobas.hobune.stream/wayback/20220612213717im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
GameObject.Find() work on inactive objects 16 Answers
GameObjects deactivate when Unity starts 0 Answers
Why won't my object activate? 0 Answers
How to make something happen when an object isn't active 1 Answer