OnCollisonEnter2D is not working

I have two objects, Enemy_Soldier and Ruby. This objects must collide and make damage to Rubie’s HP on collison, somehow the program which must to perform that works is not working. The next is enemy script-code, and Ruby script-code.

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

public class EnemyController : MonoBehaviour
{
    public float speed;
    public float changeTime = 3.0f;
    public bool vertical;
  
    Rigidbody2D rigidbody2D;
    float timer;
    int direction = 1;
  
    // Start is called before the first frame update
    void Start()
    {
        rigidbody2D = GetComponent<Rigidbody2D>();
        timer = changeTime;
    }
  
    void Update()
    {
        timer -= Time.deltaTime;
      
        if (timer < 0)
        {
            direction = -direction;
            timer = changeTime;
        }
    }
  
    void FixedUpdate()
    {
        Vector2 position = rigidbody2D.position;
      
        if (vertical)
        {
            position.y = position.y + Time.deltaTime*speed*direction;
        }
        else
        {
            position.x = position.x + Time.deltaTime*speed*direction;
        }
      
        rigidbody2D.MovePosition(position);

    void OnCollisonEnter2D(Collision2D other)
    {
        Idiotic_Ruby_Controller player = other.gameObject.GetComponent<Idiotic_Ruby_Controller>();
      
        if (player != null)
        {
            player.ChangeHealth(-1);
        }
    }
      
    }

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

public class Idiotic_Ruby_Controller : MonoBehaviour
{
    public int maxHealth = 5;
  
    public float time_invincible = 2.0f;

    public float maxSpeed = 3.0f;
  
    public int health { get { return currentHealth; }}

    int currentHealth;
  
    bool is_invincible;
    float invincible_timer;

    Rigidbody2D rigidbody2d;
    float horizontal;
    float vertical;

    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
        currentHealth = maxHealth;
    }

    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
      
        if (is_invincible)
        {
            invincible_timer -= Time.deltaTime;
            if (invincible_timer < 0)
                is_invincible = false;
        }
    }

    void FixedUpdate()
    {
        Vector2 position = rigidbody2d.position;
        position.x = position.x + maxSpeed*horizontal*Time.deltaTime;
        position.y = position.y + maxSpeed*vertical*Time.deltaTime;
      
        rigidbody2d.MovePosition(position);
    }
  
    public void ChangeHealth(int amount)
    {
        if (amount < 0)
        {
            if (is_invincible)
                return;

            is_invincible = true;
            invincible_timer = time_invincible;
        }
            currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
            Debug.Log(currentHealth + "/" + maxHealth);
    }
}

After collision is happens nothing, but in the left bottom corner must be massage about Health of Ruby decreasing.

This is Enemy Inspector program.

And this is Ruby Inspector program.

It appears you are correctly using .MovePosition(), so that rules out the most common cause of this.

Next step might be to make a cube with a Rigidbody, collider and script on it and see if you can get that to interact with ANYTHING (eg, respond to the messages you want), just dropping one in, dropping the script on while the game is running. Doing stuff like that, like pausing the game and jamming stuff right into the scene at runtime, that can often show you what is going wrong.

Oh also: line 50 on the top… print out other.name with Debug.Log() … verify it is who you think it should be.

And just in general, since you must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

Two things:

  1. You have not spelled your OnCollisionEnter2D method correctly (you have put it as OnCollisonEnter2D)
  2. Your OnCollisionEnter2D method is inside your FixedUpdate method. Move it so it is outside the FixedUpdate method and see if that fixes anything by moving lines 48-56 (in your first script) so they are after line 58.

Once you fixe both of those, does it change anything?

Not helped.[quote=“Kurt-Dekker, post:2, topic: 889337, username:Kurt-Dekker”]
Oh also: line 50 on the top… print out other.name with Debug.Log() … verify it is who you think it should be.
[/quote]
Not worked.Assets\Scripts\EnemyController.cs(52,25): error CS1061: 'Collision2D' does not contain a definition for 'name' and no accessible extension method 'name' accepting a first argument of type 'Collision2D' could be found (are you missing a using directive or an assembly reference?)[quote=“Kurt-Dekker, post:2, topic: 889337, username:Kurt-Dekker”]
And just in general, since you must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.
[/quote]
I have tried, but debug program caused a lot of errors itself. Me no familiar with all this names and parameters.[quote=“Kurt-Dekker, post:2, topic: 889337, username:Kurt-Dekker”]
Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);
[/quote]
It also makes me mad…[quote=“Kurt-Dekker, post:2, topic: 889337, username:Kurt-Dekker”]
If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.
[/quote]
Good thing, I have noted it.[quote=“Kurt-Dekker, post:2, topic: 889337, username:Kurt-Dekker”]
You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

[/quote]
I have read it all, but understand a low amount.

Cursed spelling… I have fixed it, but still not helped.[quote=“Kurt-Dekker, post:2, topic: 889337, username:Kurt-Dekker”]
2. Your OnCollisionEnter2D method is inside your FixedUpdate method.
[/quote]
Son of the… FixedUpdate! :face_with_spiral_eyes: It is worked! Why this idiotic program don’t working inside the FixedUpdate program? I mean, it is simply updating things over time with high rate.

My gratitude to the users who helped! Resolved! And now me can move further in this in-build instruction to introduction into Unity working.

Because the OnCollisionEnter2D does not belong in that method. If you put a method inside another method, as you did, then the only thing that can call that method is the one it is inside (in your case FixedUpdate could call OnCollisionEnter2D, but nothing else can) as it makes it local scope to that method. This means that the engine itself does not have access to that method because your nested method can only be called from within FixedUpdate, and therefore the physics engine can’t reach it.
It would be like complaining that the “idiotic program” doesn’t call your Update method if you put it as a method inside the Start method.
All the Unity methods are supposed to be at the class level (ie: inside the class) not inside other methods within the class.
At least you know this for the future.

Me spent almost two days to solve that problem and if no this forum, I probably may spent much more time… It is sometimes hard to me to understand what a heck this Unity doing, even on minimal level.

For future reference, for any tiny problem like this, just set what you’re doing aside, make a fresh scene, fresh script, get it working. There is example code for almost everything right on the Unity documentation pages:

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html

Until you get that example code running, don’t even THINK about your project. As soon as the example code runs, see how it differs from your project.

BAM, problem solved in a few minutes, not a few days.

After all…

I have spent few hours to read that stupid scholastic manuals in Unity Documentation (I wander why I need to download 600 MB documentation if I still need to search online), which made for those who understand all abbreviatures and keywords of C# programming language, I don’t understand how to solve my problem from those particularly the above mentioned by you Mr. Dekker example. It is only make me feel no good, but the community forum saved mineself.[quote=“Kurt-Dekker, post:7, topic: 889337, username:Kurt-Dekker”]
After all…
[/quote]
It is not “debugging”, it is only picture from the pathetic Hollywood movie.