Hi,
Im still in the learning process of Unity,
and I was wondering how I can make certain objects do damage.
So if my character takes a certain amount of damage it dies and restarts the game.
Thanks!
Hi,
Im still in the learning process of Unity,
and I was wondering how I can make certain objects do damage.
So if my character takes a certain amount of damage it dies and restarts the game.
Thanks!
Firstly, Your character should have health:
public int health = 100;
and your enemy should have damage:
public int damage = 10;
On your character you should have a function to take damage:
public void Damaged(int damage)
{
health -= damage;
if(health =< 0)
{
// Reload your scene using the new SceneManager
}
}
On your enemy you should have a function which gets called to deal the damage - On a collision?
void OnCollisionEnter(Collision col)
{
// check If you collide with the player
// I dont remember if you check it with col.tag - needs checking
if(col.tag == "Player")
{
col.GetComponent<ScriptWhichHasHealth>().Damaged(damage)
}
}
EDIT:
This may not be prefect but it is the sort of approach that I would take.
(may have a couple of small error within the code - is untested)
This is a great place to learn new things: Unity Learn
One of which is what you need.
do u put the code in void update or void start
Thanks! :)![]()
something messed up with the last part, it says col doesnt contain a definition for getcomponent
There are a couple of syntax errors in that post however they should be fairly easy to solve. This one for example instead of col.GetComponent should probably be col.gameObject.GetComponent