Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by RaiderA528 · Sep 26, 2011 at 01:26 AM · guihudhealthbarnullreference

Help!!! NullReferenceException: Object reference not set to an instance of an object UnityEngine.GUI.DrawTexture

Okay I have a character code and I want a .PNG of a "Full Health Bar" to be draw on the bottom left of the screen while the character is on 100 health. It keeps giving me the Null reference and something about an Instance error. Anyway here's my character controller code. Any help would be great, i don't have a clue what's wrong. :( Thanks!!!

var Health = 100;

static var dead = false;

private var walkSpeed : float = 0.5;

private var gravity = 5.0; //New variable for code involving gravity

private var moveDirection : Vector3 = Vector3.zero;

private var charController : CharacterController;

private var strength = 0.5; //New variable for code involing objects the player collides with

//function that enables the keyboard cursors to transform the player direction + play associated annimations

function Start(){

 charController = GetComponent(CharacterController);

}

function Update ()

{

 if (Health <=100)

 {

 GUI.DrawTexture(Rect(30,530,80,30), Resources.Load("healthbar_full"));

 }

 

 if (Health <=1)

 {

 dead = true;   

 }

 

 if(charController.isGrounded == true) //using this code, the character animations should only play while the character is grounded

 {

 if(Input.GetAxis("Vertical") > .1)//input = upward cursor key or W key

 {

     walkSpeed = 0.6;

 }



 if(Input.GetAxis("Vertical") < -.1)//input = downward cursor key or S key

 {

     walkSpeed = 0.5;

 }



 transform.eulerAngles.y += Input.GetAxis("Horizontal");

 moveDirection = Vector3(0,0, Input.GetAxis("Vertical"));

 moveDirection = transform.TransformDirection(moveDirection);

 }

 moveDirection.y -= gravity * Time.deltaTime;

 charController.Move(moveDirection*walkSpeed);

}

function OnControllerColliderHit(hit : ControllerColliderHit) //moves any game object with a rigidbody+collider component based on the strength variable

{

 var body : Rigidbody = hit.collider.attachedRigidbody;

 if (body){

     var pushDir = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z);

     body.velocity = pushDir*strength*10;

 }

}

function OnTriggerEnter(hit : Collider){

if(hit.gameObject.tag == "EvilShot")

{ Health -= 10;

Destroy(hit.gameObject);

}

if(hit.gameObject.tag == "SlowingSludgePlane")

{ walkSpeed = 0.1;

}

}

function OnTriggerExit(hit : Collider){

if(hit.gameObject.tag == "SlowingSludgePlane")

{ walkSpeed = 0.5;

}

}

function LateUpdate()

{ if(dead)

{

 transform.position = Vector3(3386.499,211.0097,707.7693);



 dead = false;



}

}

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image RaiderA528 · Sep 26, 2011 at 12:19 AM 0
Share

NOTE!!! *It says the Error is caused by the line :

if (Health <=100)

{

GUI.DrawTexture(Rect(30,530,80,30), Resources.Load("healthbar_full"));

}

and the error is exactly: "NullReferenceException: Object reference not set to an instance of an object UnityEngine.GUI.DrawTexture (Rect position, UnityEngine.Texture image, Scale$$anonymous$$ode scale$$anonymous$$ode, Boolean alphaBlend, Single imageAspect) (at C:/BuildAgent/work/842f9557127e852/Runtime/ExportGenerated/Editor/GUI.cs:122) UnityEngine.GUI.DrawTexture (Rect position, UnityEngine.Texture image) (at C:/BuildAgent/work/842f9557127e852/Runtime/ExportGenerated/Editor/GUI.cs:119) Character_Controls.Update () (at Assets/Custom_Scripts/Character_Controls.js:20)" I'm very new to coding so any would be Epic!!! Thanks!!!

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by CHPedersen · Sep 26, 2011 at 06:56 AM

Two things:

First of all, the error happens because Resources.Load was unable to locate an asset named "healthbar_full". In consequence, it returns null instead of a texture when it attempts to load it. Then, when GUI.DrawTexture expected a texture for an argument so it could draw it, it received null instead. Then it threw up all over the place and cast that exception. (Its reference to the texture it was supposed to draw was null, i.e. a "NullReferenceException").

To fix this, you have to make absolutely sure there's a file of a appropriate format (png, bmp, etc.) with that exact filename, and it must be located in a folder called Resources, and that folder should be in your Assets folder.

Second of all, once you have it working, you should modify your code so that the call to Resources.Load isn't embedded inside the call to GUI.DrawTexture. Think about it this way: Resources.Load actually goes to the harddrive and fetches your texture for you. Then you draw it, but when you're done drawing it, it gets thrown away again because you're not saving it. Then on the next frame, you ask Resources.Load to run to the harddrive and fetch you a new copy of the same texture. Why throw it away every frame, only to reload it again, every frame?

Instead, save it to a Texture2D variable in the Start function, and then pass that to GUI.DrawTexture, like this:

 Texture2D healthBar;
 
 // Load the texture
 void Start()
 {
     healthBar = (Texture2D)Resources.Load("healthbar_full");
 }
 
 // Use the loaded texture
 void Update()
 {
     GUI.DrawTexture(new Rect(30, 530, 80, 30), healthBar);
 }

This was in C#, I hope you're okay with that. You're not meant to actually use that, it's just to give you an idea how to cache that texture. ;)

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by RaiderA528 · Sep 26, 2011 at 04:27 PM

Thanks very much, I realised a little before I read this that my original way wasn't gonna work at all for what I needed, or at least there'd be a better way. Thanks for the info on resources.load though, fetching a picture every frame just to throw it away every frame would seem really bad for a health bar. :P eventually is settled for this. var healthbar_full : GUITexture;

var healthbar_DAM1 : GUITexture;

var healthbar_DAM2 : GUITexture;

var healthbar_DAM3 : GUITexture;

var healthbar_DAM4 : GUITexture;

var healthbar_DAM5 : GUITexture;

var healthbar_DAM6 : GUITexture;

var healthbar_zero : GUITexture;

var Health = 8;

static var dead = false;

private var walkSpeed : float = 0.5;

private var gravity = 5.0; //New variable for code involving gravity

private var moveDirection : Vector3 = Vector3.zero;

private var charController : CharacterController;

private var strength = 0.5; //New variable for code involing objects the player collides with

//function that enables the keyboard cursors to transform the player direction + play associated annimations

function Start(){

 charController = GetComponent(CharacterController);

 healthbar_full.enabled = false;

 healthbar_DAM1.enabled = false;

 healthbar_DAM2.enabled = false;

 healthbar_DAM3.enabled = false;

 healthbar_DAM4.enabled = false;

 healthbar_DAM5.enabled = false;

 healthbar_DAM6.enabled = false;

 healthbar_zero.enabled = false;

}

function Update ()

{

 if (Health <=8)

 {

 healthbar_full.enabled = true;

 }

 if (Health <=7)

 {

 healthbar_DAM1.enabled = true;

 healthbar_full.enabled = false;

 }

 if (Health <=6)

 {

 healthbar_DAM2.enabled = true;

 healthbar_DAM1.enabled = false;

 healthbar_full.enabled = false;

 }

 if (Health <=5)

 {

 healthbar_DAM3.enabled = true;

 healthbar_DAM2.enabled = false;

 healthbar_DAM1.enabled = false;

 healthbar_full.enabled = false;

 }

 if (Health <=4)

 {

 healthbar_DAM4.enabled = true;

 healthbar_DAM3.enabled = false;

 healthbar_DAM2.enabled = false;

 healthbar_DAM1.enabled = false;

 healthbar_full.enabled = false;

 }

 if (Health <=3)

 {

 healthbar_DAM5.enabled = true;

 healthbar_DAM4.enabled = false;

 healthbar_DAM3.enabled = false;

 healthbar_DAM2.enabled = false;

 healthbar_DAM1.enabled = false;

 healthbar_full.enabled = false;

 }

 if (Health <=2)

 {

 healthbar_DAM6.enabled = true;

 healthbar_DAM5.enabled = false;

 healthbar_DAM4.enabled = false;

 healthbar_DAM3.enabled = false;

 healthbar_DAM2.enabled = false;

 healthbar_DAM1.enabled = false;

 healthbar_full.enabled = false;

 }

 if (Health <=1)

 {

 healthbar_zero.enabled = true;

 healthbar_DAM6.enabled = false;

 healthbar_DAM5.enabled = false;

 healthbar_DAM4.enabled = false;

 healthbar_DAM3.enabled = false;

 healthbar_DAM2.enabled = false;

 healthbar_DAM1.enabled = false;

 healthbar_full.enabled = false;

 dead = true;   

 }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Splitscreen w/ different GUIs on each camera 2 Answers

How to make a texture cover an entire GUI box 0 Answers

Shrink GUI 1 Answer

CoolDown Animation on the GUI 1 Answer

GuiTexture above 3D objects 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges