- Home /
C# Object reference not set to an instance of an object
it is at line 46, this is the code:
using UnityEngine;
using System.Collections;
public class PlayerScript : MonoBehaviour {
public int health = 100;
private int damage;
public IList respawns;
private float time;
private float hrdelay = 0.25f;
public int healthRegen = 1;
// Use this for initialization
void Start () {
}
public float HealthDamage(){
return health;
}
public void DoDamage (int damageParam){
health = health - damageParam;
}
// Update is called once per frame
void Update () {
Ray ray = new Ray(transform.position, transform.up);
RaycastHit hit;
if (Time.time > time)
{
time = Time.time + hrdelay;
health = health + healthRegen;
}
if (health < 0)
{
respawns = GameObject.FindGameObjectsWithTag("Respawn");
if (respawns == null)
{
print ("No place to respawn.");
}
else
{
foreach (GameObject respawn in respawns)
{
if (hit.collider.gameObject.tag == "Player")
{
GameObject noGo = respawn;
print ("No Respawn.");
}
else
{
GameObject Go = respawn;
Vector3 go = Go.transform.position;
Vector3 temp = transform.position;
temp.x = go.x;
temp.y = go.y;
temp.z = go.z;
transform.position = temp;
print ("You respawned.");
}
}
}
}
}
}
Answer by rhys_vdw · Jul 24, 2013 at 01:39 PM
You are not actually performing a raycast, so your RaycastHit object will have null values for all its members.
Read here for more information on how to do this correctly.
Basically change line 46 to:
if( Physics.Raycast( ray, out hit ) && hit.collider.gameObject.tag == "Player" ) {
Unfortunately, however, your code doesn't make any sense. You'll need to change more than this for the script to do anything useful. I'd need more information about what you were trying to achieve to help you further.
This was just health and it was meant to be accessed by other scripts
The part that doesn't make sense is this bit:
if (hit.collider.gameObject.tag == "Player")
{
GameObject noGo = respawn;
print ("No Respawn.");
}
The health stuff looks reasonable.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110746im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Swipe function 2 Answers