Enemy Script works with one enemy but gets broken if I make a copy of the enemy

My code works as in Rick’s video, but if I make a copy of the enemy it stops working.
If I disable the copy’s Game Object, leaving only one enemy, it works.

Video: Unity 2d Course Tilevania - YouTube

PS:(The barrell is the enemy, while the crates are “platform layer”. They are allowed to collide in the matrix and the enemy box collider is trigger.)

PS2:(Sergey is the Player)

This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{
    Rigidbody2D enemyBody;
    BoxCollider2D enemyCollider;
    [SerializeField] float enemyMovementSpeed = 1f;   
    
    
    void Start()
    {
        enemyBody = FindObjectOfType<Rigidbody2D>();
        enemyCollider = FindObjectOfType<BoxCollider2D>();
    }

    void Update()
    {
        enemyBody.velocity = new Vector2 (enemyMovementSpeed, 0f);    
    }

    void OnTriggerExit2D(Collider2D other) 
    {
        Debug.Log("Bonk");
        enemyMovementSpeed = -enemyMovementSpeed;
        FlipEnemy();
    }

    void FlipEnemy()
    {
        transform.localScale = new Vector2 (-(Mathf.Sign(enemyBody.velocity.x)), 1f);
    }              
}

I tried (without success):
-making OnTriggerExit2D private (private void OnTriggerExit2D);
-working with both prefabs and simple Game Object’s copies;
-making the enemies children of two different empty Game Objects.

Thanks!

This is probably where you’re having your issues. This method looks for the first instance of the script in your scene, so both enemies would be finding the same enemy and trying to control it as it is itself.

The easiest fix would be to use GetComponent method instead of FindObjectOfType.

1 Like

Thank you very much, it works!
Rick wrote GetComponent as well, I can’t undestand how I couldn’t spot the difference, maybe I needed a pause! :man_facepalming:

You’re welcome. They’re easy enough to get mixed up especially when you’re getting the hang of the engine. Good luck with the rest of your projects.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms