Unity Collision Remove then Add back

Multi tool use
Multi tool use


Unity Collision Remove then Add back



I have objects that scroll across the screen and do so endlessly.
I want to remove the object when touched (I got that part) SetActive/Destroy.
I am trying to add the objects back to the scene so they can be re-used.



How would I go about this?


if (col.gameObject.tag == "Coin"){
coinCount++;
coins.text = coinCount.ToString();

// Save Coins
PlayerPrefs.SetInt("Coins", coinCount);
col.gameObject.SetActive(false);
}



The Code Above is in a -> OnTriggerEnter2D(Collider2D){}


OnTriggerEnter2D(Collider2D){}


// Waits Seconds to put coins in correct spot
IEnumerator afterSeconds(GameObject x)
{
//x.SetActive(false);

yield return new WaitForSeconds(5f);//5f

//x.SetActive(true);
}




2 Answers
2



You could use MonoBehavior.Invoke() and set a class variable to the collider, but this would be messy if you have collisions occurring before the re-enabling step. Instead I would use a Coroutine.


MonoBehavior.Invoke()


Coroutine


if (col.gameObject.tag == "Coin"){
coinCount++;
coins.text = coinCount.ToString();

// Save Coins
PlayerPrefs.SetInt("Coins", coinCount);
StartCoroutine(afterSeconds(col.gameObject)); //hide, delay, show
}



and then:


// Waits Seconds to put coins in correct spot
IEnumerator afterSeconds(GameObject x)
{
x.SetActive(false);
yield return new WaitForSeconds(5f);
x.SetActive(true);
}





Thanks for the answer, Now I realize how simple my mistake was forgetting the Coroutine
– shane
Jul 3 at 2:25



What you may be looking for is object pooling. This is a system which manages the instantiation of dynamic amounts of GameObjects, by not destroying and instantiating them, but instead making them invisible and reusable. If the pool is running out of needed objects (because too many are in use at once), it can instantiate additional objects as needed. Usually there are assets which do that, but I guess it can be coded on your own as well. Even the official Unity tutorials mentions that and classifies that as beginner level: Object Pooling.
What then happens is that you simply replace all Instantiate methods with your InstantiatePool methods.



So in case you don't want to explicitely make GameObjects respawn in fixed delays, but allow a manager script to handle the spawning as wanted, that may be what you are looking for.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

wAWiBbzJB,T62tGs ri8YlC YEA IKOWPbOPX28g,31D,Th1o4ng6r0boIRmAxT3B CtL
KMRFTzn4iTyYr7jf2WY4CgMXk,qjmAmdpRcrZFH8e7NDQRQ7TqK O BV6UaG85oa0hIvG,NvI5,IX2Wy,fSKVmwa

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications