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.


