- Home /
 
How to fix, that every clone changes color, if I shoot at only one clone?
I have an issue. I have a function in my enemy script, that if the enemy collides with the bullet, he changes the color for a short amount of time. My problem is, that if i have 2 Enemy's and I shoot at one of them, both are changing the color. How to fix that? Only the enemy, that I shoot on should change the color, not the one that I didn't shoot on.
Here's my script:
 void Start()
 {
     player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
     rb = GetComponent<Rigidbody2D>();
     mat.color = defaultcolor;
 }
 void Update()
 {
     Vector3 direction = player.position - transform.position;
     float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f;
     transform.rotation = Quaternion.Euler(0, 0, angle);
     direction.Normalize();
     movement = direction;
     moveEnemy(direction);
 }
 void moveEnemy(Vector2 direction)
 {
     rb.MovePosition((Vector2)transform.position + (direction * speed));
 }
 private void OnCollisionEnter2D(Collision2D collision)
 {
     if (collision.gameObject.tag == "Bullet")
     {
         rb.velocity = new Vector2(0, 0);
         if (HP >= 0)
         {
             StartCoroutine("ChangeColorOnHit");
         }
         HP--;
         Destroy(collision.gameObject);
         if (HP <= 0)
         {
             Destroy(gameObject);
             ParticleSystem particleclone = Instantiate(deathparticle, transform.position, Quaternion.identity);
             
         }
         if (collision.gameObject.tag == "EnemyBullet")
         {
             rb.velocity = new Vector2(0, 0);
         }
     }
 }
 private void OnCollisionExit2D(Collision2D collision)
 {
     if (rb.velocity.x > 0 || rb.velocity.x < 0 || rb.velocity.y > 0 || rb.velocity.y < 0)
     {
         rb.velocity = new Vector2(0, 0);
     }
 }
 IEnumerator ChangeColorOnHit()
 {
     mat.color = colorOnHit;
     yield return new WaitForSeconds(0.1f);
     mat.color = defaultcolor;
 }
 
              You need to change instantiated material properties instead of changing global material stuff: https://answers.unity.com/questions/785135/create-a-new-instance-of-an-object-not-a-clone.html
Your answer
 
             Follow this Question
Related Questions
Generating 2D collisions for maze 0 Answers
Trouble Descaling 2D object 1 Answer
Display 1 No cameras rendering when player collides with enemy 1 Answer
Simple top-down 2D collision 2 Answers
Ignore collision for all except one 1 Answer