Hello!
I have a level where the player has to throw cogs at some robots to fix them. I want to load the next level as soon as the player fixes all the robots in the scene. I thought about making an int variable counter and adding +1 to the variable in the Fixed() function, and then in Update checking if the counter has reached the number of robots in the scene. But this doesn’t seem to work.
I thought also about making some kind of function that checks if all the robots in the scene are playing the “Fixed” animation. But I have no idea how to do it.
Can anyone help me?
This is my script for the robot:
using UnityEngine;
using UnityEngine.SceneManagement;
public class Enemy : MonoBehaviour
{
public float speed;
public float timeToChange;
public bool horizontal;
public GameObject smokeParticleEffect;
public ParticleSystem fixedParticleEffect;
public AudioClip hitSound;
public AudioClip fixedSound;
Rigidbody2D rigidbody2d;
float remainingTimeToChange;
Vector2 direction = Vector2.right;
bool repaired = false;
// ===== ANIMATION ========
Animator animator;
// ================= SOUNDS =======================
AudioSource audioSource;
void Start ()
{
rigidbody2d = GetComponent<Rigidbody2D>();
remainingTimeToChange = timeToChange;
direction = horizontal ? Vector2.right : Vector2.down;
animator = GetComponent<Animator>();
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if(repaired)
return;
remainingTimeToChange -= Time.deltaTime;
if (remainingTimeToChange <= 0)
{
remainingTimeToChange += timeToChange;
direction *= -1;
}
rigidbody2d.MovePosition(rigidbody2d.position + direction * speed * Time.deltaTime);
animator.SetFloat("ForwardX", direction.x);
animator.SetFloat("ForwardY", direction.y);
}
void OnCollisionStay2D(Collision2D other)
{
if(repaired)
return;
RubyController controller = other.collider.GetComponent<RubyController>();
if(controller != null)
controller.ChangeHealth(-1);
}
public void Fix()
{
animator.SetTrigger("Fixed");
repaired = true;
smokeParticleEffect.SetActive(false);
Instantiate(fixedParticleEffect, transform.position + Vector3.up * 0.5f, Quaternion.identity);
//we don't want that enemy to react to the player or bullet anymore, remove its reigidbody from the simulation
rigidbody2d.simulated = false;
audioSource.Stop();
audioSource.PlayOneShot(hitSound);
audioSource.PlayOneShot(fixedSound);
}
}