Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm facing with NullReferenceException Error in Unity2D

I’m trying to find solution to this problem for almost 2 days and I couldn’t find any answers.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBar : MonoBehaviour
{
    public float sizeNormalized;
    private Transform bar;
    // Start is called before the first frame update
    private void Start()
    {
        Transform bar = transform.Find("Bar");
    }

    public void SetSize(float sizeNormalized){
        bar.localScale = new Vector3(sizeNormalized,1f);
    }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It throws error at line 16, bar.localScale = new Vector3(sizeNormalized,1f);

Please help. Thanks much.

>Solution :

Transform bar = transform.Find("Bar");

Declares and defines a new local variable inside the scope of the method. You want to define your private variable, so you should just write

bar = transform.Find("Bar");

I’m not sure if that’s enough to solve your problem but its a good start.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading