Is there a way around my problem? I’m using this script to draw out an arrow to where the player is aiming and I get an error that says “NullReferenceException: Object reference not set to an instance of an object”, “GetPlayerPos.Update () (at Assets/Scripts/GetPlayerPos.cs:13)”.
Basically, when one of the players is dead the script can’t find “PlayerOne” because the gameobject is destroyed.
using UnityEngine;
using System.Collections;
public class GetPlayerPos : MonoBehaviour
{
public string Whatplayer;
Vector3 PlayerPos = Vector3.zero;
// Update is called once per frame
void Update ()
{
GameObject thePlayer = GameObject.Find(Whatplayer);
Movement playerScript = thePlayer.GetComponent<Movement>();
if (!playerScript.dead)
{
PlayerPos.x = playerScript.transform.position.x + playerScript.chargeX / 10;
PlayerPos.y = playerScript.transform.position.y + playerScript.chargeY / 10;
PlayerPos.z = playerScript.transform.position.z;
transform.position = PlayerPos;
}
}
}
Oh hey, you tried to help me last time
What you suggested didn’t work for me, I’m probably doing it wrong. I’ve tried so many things and nothing seems to do the trick for me
The Movement script you are looking for does not exist on thePlayer, hence playerScript is null. Have you forgotten to add it? Have you previously destroyed it? Or are you looking in the wrong place?
doh, tracked across to the wrong line from the line number… principle still holds. If you “find” or “getcomponent” you can check if it returned something or null before attempting to use it.
The movement script is on the player but when that player dies the player gets destroyed thats why. I want to “kill” the player without it being a problem for the script.
Then you either have to reassign the new player when you spawn it to the GetPlayerPos, or look for a new one.
I’d suggest looking for tags rather than looking for gameobject names.
using UnityEngine;
using System.Collections;
public class GetPlayerPos : MonoBehaviour
{
public string whatplayer;
Vector3 playerPos = Vector3.zero;
private Movement playerScript;
void Update ()
{
// Make sure playerScript exists.
if (playerScript)
{
if (!playerScript.dead)
{
playerPos.x = playerScript.transform.position.x + playerScript.chargeX / 10f;
playerPos.y = playerScript.transform.position.y + playerScript.chargeY / 10f;
playerPos.z = playerScript.transform.position.z;
transform.position = playerPos;
}
}
else
{
// No playerScript, look for another.
GameObject thePlayer = GameObject.Find(whatplayer); // Should probably replace with FindWithTag
if (thePlayer) // We found the player we're looking for, can we find its Movement component?
{
playerScript = thePlayer.GetComponent<Movement>();
}
}
}
}