can someone help me with my code error
I am just starting out making a game and all is going well exept for my defense of the player for some reason. it shows up as a
NullReferenceException: Object reference not set to an instance of an object hurtplayer.OnCollisionEnter2D (UnityEngine.Collision2D other) (at Assets/script/hurtplayer.cs:20)
can someone please help me find out were I cant seam to find the problem.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerstats : MonoBehaviour {
public int currentlvl;
public int exp;
public int[] tolvlup;
public int[] hplevels;
public int[] attacklevels;
public int[] defenselevels;
public int chealth;
public int cattack;
public int cdeffense;
private playerhealth playerhealth1;
void Start () {
chealth = hplevels [1];
cattack = attacklevels [1];
cdeffense = defenselevels [1];
playerhealth1 = FindObjectOfType <playerhealth> ();
}
void Update () {
if (exp >= tolvlup [currentlvl]) {
//currentlvl++;
levelup ();
}
}
public void addexp(int expadd){
exp += expadd;
}
public void levelup (){
currentlvl++;
chealth = hplevels [currentlvl];
playerhealth1.playermhealth = chealth;
playerhealth1.playerchealth += chealth - hplevels[currentlvl - 1];
cattack = attacklevels [currentlvl];
cdeffense = defenselevels [currentlvl];
}
}
using UnityEngine;
using System.Collections;
public class hurtplayer : MonoBehaviour{
public int damagetogive;
private int currentdamage;
private playerstats ps;
void start(){
ps = FindObjectOfType<playerstats> ();
}
void update(){
}
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.tag == "Player") {
currentdamage = damagetogive - ps.cdeffense;
//currentdamage = damagetogive;
other.gameObject.GetComponent<playerhealth> ().hurtplayer (currentdamage);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerhealth : MonoBehaviour {
public int playermhealth;
public int playerchealth;
// Use this for initialization
void Start () {
playerchealth = playermhealth;
}
// Update is called once per frame
void Update () {
if (playerchealth < 0) {
gameObject.SetActive (false);
}
if (playerchealth > playermhealth) {
playerchealth = playermhealth;
}
}
public void hurtplayer(int currentdamage)
{
playerchealth -= currentdamage;
}
public void setmaxhealth()
{
playermhealth = playerchealth;
}
}
Answer by UltraGearGames · Jan 25, 2019 at 09:28 PM
one of the gameobjects doesnt have a trigger on it. Simple stuff. Also dont forget to add a rigidbody (or rigidbody2D) to at least one of the 2 objects!
Your answer

Follow this Question
Related Questions
Help with NullReferenceException 0 Answers
Not sure what this error is telling/asking me to do? 1 Answer
Null Reference Error 0 Answers
NullReferenceException... but it was just set...? 1 Answer
Cannot access 2D array element 1 Answer