Hi,
I have a objectA with script,
When i play, script work perfect but if i disable my objectA and i enable after, script not work (yet my object is well returned on enable).
You know why?
thank you for your help
Might have to show us some code, no idea what you are doing in your script or what is or isn’t suppose to be working.
Oups, i have forget the script on my first message ^^’
script work on the game but if i disable and enable, after script is enable it does not work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrueEverySecond : MonoBehaviour
{
public GameObject[] Objects = new GameObject[0];
private List<GameObject> tempObjects = new List<GameObject>();
void Start()
{
StartCoroutine(SelectRandomObject()); // starts the function
}
IEnumerator SelectRandomObject()
{
for (int i = 0; i < Objects.Length; i++)
{
tempObjects.Add(Objects[i]); // add all items into list
}
while (true)
{
yield return new WaitForSeconds(8.0f);
GameObject SelectedObject = tempObjects[Random.Range(0, tempObjects.Count)];
SelectedObject.SetActive(true);
tempObjects.Remove(SelectedObject); // removes item for list so cannot be selected again
// if you want to list to be empty before restoring
if (tempObjects.Count <= 0)
{
tempObjects.Clear();
for (int i = 0; i < Objects.Length; i++)
{
tempObjects.Add(Objects[i]); // add all items into list
}
}
}
}
}
When you disable an object all scripts stop running even if you renable it, one way to get around this is to have a reactivate bool in ur update loop, but you must make sure you are setting this variable to false when deactivating a gameobject
Public bool reactivate = true;
Void Update ()
{
If (reactivate)
{
// run code
Reactivate = false; // runs once to gst corutines, starting variavles etc working again
}}
So your coroutine stops running, correct?
If you disable the gameobject the script is on (using SetActive), the coroutine will stop running, thus when you turn it back on, it doesn’t resume. If you disable the script itself, it will continue to run, which may not be the result you want.
So, either you need to use OnEnable to retrigger the coroutine or just turn off the script, but that would keep it running if that is the desired result)
No…Just use OnEnable to restart the coroutine.
Yes, OnEnable() is the answer. You could simply do this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrueEverySecond : MonoBehaviour
{
public GameObject[] Objects = new GameObject[0];
private List<GameObject> tempObjects = new List<GameObject>();
void Start()
{
StartCoroutine(SelectRandomObject()); // starts the function
}
void OnEnable()
{
StartCoroutine(SelectRandomObject()); // starts the function
}
...
Thank you everyone!
Work perfect with :
void OnEnable()
{
StartCoroutine(SelectRandomObject()); // starts the function
}