Hi, I am pretty new to C# and unity at the start, plus I am doing this out of my interest, so my question could be basic. However it has bugged me for so long, that I couldn’t get it over even after I research it over the internet. I have also posted this to unity answer, but it is waiting to be approved, so i figure i will post it here too for the moment (if my post is against any rules, plz let me know, i am willing to correct whatever mistake i have made).
Anyway, here is my question, I have got this error NullReferenceException: Object reference not set to an instance of an object two times over my script.
The first time is when I wanted to set the respawn action only execute after the player enters the “Dying state”, I have use Debug.Log to ensure it successfully enters the Dying state, but when I click the respawn button after the player dies, the error pops up.
The second error happens whenever I press the attack button, which I intend to let my player throw grenade or whatever.
Codes as bellow (I have only pasted the relevant code, just so it may be easier to read)
My PlayerController script, and it works fine
void Update () {
if(GetComponent().Died!=true){
Dying=false;
#region player alive movement
.
.
.
#endregion
}else{
Dying=true;
animator.SetBool(“Die”, true);
targetSpeed=0;
currentSpeed = IncrementTowards(currentSpeed, targetSpeed,slideDeceleration);
amountToMove.x = currentSpeed;
amountToMove.y -= gravity * Time.deltaTime;
playerPhysics.Move(amountToMove * Time.deltaTime);
}
//Attack
if (Input.GetButtonDown(“LRangeAttack”)) {
//attack.Throw();
Debug.Log(“throwing now”);
GetComponent().Throw();
throwing = true;
animator.SetBool(“Throwing”,true);
}
then here is my GameManager script, where the first error pops in when I want to respawn
NullReferenceException: Object reference not set to an instance of an object GameManager.Update () (at Assets/Scripts/GameManager.cs:30)
which is line if(GetComponent().Dying=true) in GameManager script
private void Update() {
if (Input.GetButtonDown(“Respawn”)) {
if(GetComponent().Dying=true)
Destroy(currentPlayer.gameObject);
SpawnPlayer(checkpoint);
}
}
and now the second errors in my PlayerAttack script, I have yet completed the function but the error still shows
NullReferenceException: Object reference not set to an instance of an object PlayerController.Update () (at Assets/Scripts/PlayerController.cs:158)
which is line GetComponent().Throw(); in PlayerController script
using UnityEngine;
using System.Collections;
public class PlayerAttack : MonoBehaviour {
public void Throw() {
Debug.Log(“THROW”);
}
}