- Home /
NullReferenceException: Object reference not set to an instance of an object ss.Update () (at Assets/ss.cs:21)
I getting this error when I play my scene . I check my component to see if everything is attach . This is an access script . The script I am accessing already dragged and drop into the script. The problem is when I press play its saying that the script is not attach. Here is my script :
using UnityEngine;
using System.Collections;
public class ss : MonoBehaviour {
public Healthbar healthbar;
public GameObject Player;
Animator anim;
void Start () {
Player = GameObject.FindGameObjectWithTag ("Player");
healthbar = Player.GetComponent <Healthbar> ();
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
{
if (healthbar.health <= 50)
{
GetComponent<Animator>().SetTrigger("fail");
AudioSource audio = GetComponent<AudioSource>();
audio.Play();
}
}
}
}
I don't think I have an answer for you but I do see a couple of things:
You have a variable for your animator "anim". You get this component in your start(), that's good. But then in the update function you are getting the component again, and aren't using the "anim" variable anymore.
//Used
GetComponent<Animator>().SetTrigger("fail");
//Possible
anim.SetTrigger("fail");
Also, you could declare your audioSource in the start function as well. Ins$$anonymous$$d of getting the component in the update function.
PS: Its not a $$anonymous$$UST that you do this. But it will make your script more efficient and well organized.
Hi, are you sure healthbar isn't null? Just print it in your Update function. If healthbar is null you should change your if statement on line 21 in if (healthbar != null && healthbar.health <= 50)
, maybe that helps.
Your answer
Follow this Question
Related Questions
NullReferenceException... 1 Answer
Material[] Object reference not set when instantiating 2 Answers
Why am I getting this error ? 2 Answers
Raycasting error 1 Answer