Hello,
I am trying to make a oncollision2D EnemyDamage is done removing health from playerStats.health, unfortunately I got the error, “Identifier expected” does anyone know what I need to put there to get the code to work? Thanks error on Collision (8,41).
Collision damage code:
using UnityEngine;
using System.Collections;
public class Collision : MonoBehaviour {
int EnemyDamage = 1;
void OnCollisionEnter2D(Collision2D)
{
playerStats.Health -= EnemyDamage;
}
}
Player Code:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
[System.Serializable]
public class PlayerStats {
public int Health = 100;
}
public PlayerStats playerStats = new PlayerStats();
public int fallBoundary = -20;
void Update () {
if (transform.position.y <= fallBoundary)
DamagePlayer (9999999);
}
public void DamagePlayer (int damage) {
playerStats.Health -= damage;
if (playerStats.Health <= 0) {
GameMaster.KillPlayer(this);
}
}
}
There are several errors in your code. If you look at the console (Window\Console on the main menu) you will see all errors in red. Here is an updated version of your code with errors fixed (there still may be one depending on the rest of your code, I have noted this at the bottom of this answer).
using UnityEngine;
using System.Collections;
public class Collision : MonoBehaviour
{
int EnemyDamage = 1;
private Player player = null;
void Start()
{
if (GameObject.FindGameObjectsWithTag("Player") != null)
{
GameObject go = GameObject.FindGameObjectsWithTag("Player")[0];
player = go.GetComponent<Player>();
}
}
void OnCollisionEnter2D(Collision2D coll)
{
if ((coll.gameObject.tag == "Player") && (player != null))
{
player.DamagePlayer(EnemyDamage);
}
}
}
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
[System.Serializable]
public class PlayerStats
{
public int Health = 100;
}
public PlayerStats playerStats = new PlayerStats();
public int fallBoundary = -20;
void Update ()
{
if (transform.position.y <= fallBoundary)
DamagePlayer (9999999);
}
public void DamagePlayer (int damage)
{
playerStats.Health -= damage;
if (playerStats.Health <= 0)
{
GameMaster.KillPlayer(this);
}
}
}
The following line
GameMaster.KillPlayer(this);
may also cause an error depending how the class GameMaster is defined. If it is a static class then you should have no problems otherwise you will need to define a reference in the Player class, something like this
public GameMaster gameMaster;
gameMaster.KillPlayer(this);
Also if you have not already done this you should tag your player as “Player”.
Your absolutely amazing dude, You saved me so much time where I would have spent pieces together little bits of references to try my best to make a script. It worked wonderfully thank you very much.
Your absolutely amazing dude, You saved me so much time where I would have spent pieces together little bits of references to try my best to make a script. It worked wonderfully thank you very much.
– MythicEclipsed