- Home /
Trying to freeze multiple gameObjects at the same time
Hi. I am trying to freeze every mace object in my game at the same time for a set time. I want them the freeze when i collide with any one of them. In my current code only the mace i collide with freezes. The script i am using to freeze has been attatched to all the maces
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
StartCoroutine(Example(5));
}
if (collision.gameObject.tag == "Surface")
{
rb.AddForce(new Vector2(0, 500));
}
}
IEnumerator Example(float time)
{
yield return new WaitForSeconds(time);
gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
}
I have attached a screenshot of the interface, with the maces and the script shown attached.
Answer by ecv80 · Nov 20, 2018 at 10:15 PM
This could be one way. This is assuming your maces script/class is named "Mace":
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
Mace[] maces=Object.FindObjectsOfType<Mace>();
foreach (Mace mace in maces)
mace.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
StartCoroutine(Example(5, maces));
}
if (collision.gameObject.tag == "Surface")
{
rb.AddForce(new Vector2(0, 500));
}
}
IEnumerator Example(float time, Mace[] maces)
{
yield return new WaitForSeconds(time);
foreach (Mace mace in maces)
mace.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
}
Also, it might be more efficient to look for the maces elsewhere than each time the player collides. Consider eliminating this line:
Mace[] maces=Object.FindObjectsOfType<Mace>();
from your OnCollisionEnter2D() and add this to your maces class instead:
public class Mace : MonoBehaviour {
static List<Mace> maces=new List<Mace>();
void Awake () {
maces.Add(this);
}
You might need to remove each on destroy, or check for null values in your foreachs.