Hello I have a instantiated object that is being destroyed in a second but I wanted to stop it from destroying if the sprite is clicked on. I have a book but the bool is not working.
GM
public GameObject anw;
public Transform[] Spots;
private float timeBtwAct;
public float actWait;
void Update()
{
Level();
}
void Level()
{
List<Transform> Fps = new List<Transform>(Spots);
if (timeBtwAct <= 0)
{
int num = 1;
for (var i = 0; i < num; i++)
{
if (Fps.Count <= 0)
return;
int randPos = Random.Range(0, Fps.Count);
Transform pos = Fps[randPos];
GameObject clone = (GameObject)Instantiate(anw, pos.position, Quaternion.identity);
AnswerScript answer = anw.GetComponent<AnswerScript>();
if (!answer.isClicked)
{
Destroy (clone, 1f);
}
}
timeBtwAct = actWait;
}
else
{
timeBtwAct-= Time.deltaTime;
}
}
Your logic is false. What your code is doing right now is instantiating a clone and checking for the answer right away, which will always have the default value because all of this is done in the same frame. So answer.isClicked will always be false and you will always be destroying the object 1 second later.
You need to change the delayed destruction to a timed one where you countdown 1 second after the instantiation and at the end you check if answer was clicked or not to destroy it.
! means not so in that if statement, you are saying ‘if isClicked is false’. isClicked is false by default so you are destroying the object just after you create it. To me, it looks like you need to change your first script and put the destroy in the answer script.
public GameObject anw;
public Transform[] Spots;
private float timeBtwAct;
public float actWait;
void Update()
{
Level();
}
void Level()
{
List<Transform> Fps = new List<Transform>(Spots);
if (timeBtwAct <= 0)
{
int num = 1;
for (var i = 0; i < num; i++)
{
if (Fps.Count <= 0)
return;
int randPos = Random.Range(0, Fps.Count);
Transform pos = Fps[randPos];
Instantiate(anw, pos.position, Quaternion.identity);
}
timeBtwAct = actWait;
}
else
{
timeBtwAct-= Time.deltaTime;
}
}
As Tsaras stated, you only ever have a reference to the most recently instantiated object, and you wait no time to check if it should be destroyed or not. By the next update you instantiate a new object, forgetting about any previous ones you instantiated.