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 /
  • Help Room /
avatar image
0
Question by Thijsx7 · Apr 19, 2016 at 04:16 PM · getcomponentmovement scriptcharacter movementsprintingstamina

NullReferenceException: Object reference not set to an instance of an object error

I am creating a sprinting mechanic but when I try to change the Speed variable of my movement script I get a NullReferenceException. I already tried everything but it keeps comming back because the getcomponent keeps failing. Thanks for helping!

Thijs

The CharacterMovement script:

 using UnityEngine;
 using System.Collections;
 
 public class CharacterMovement : MonoBehaviour {
 
     Rigidbody Rigidbody;
     public float Speed;
     public Vector3 Movement;
     // Use this for initialization
     void Start () {
         Rigidbody = GetComponent<Rigidbody>();
     }
     
     // Update is called once per frame
     public void Update () {
         float Horizontal = Input.GetAxisRaw("Horizontal");
         float Vertical = Input.GetAxisRaw("Vertical");
         Movement = new Vector3(Horizontal, 0, Vertical);
         Rigidbody.velocity = Movement * Speed;
     }
 }

 using UnityEngine;
 using System.Collections;


And the Stamina script:

 public class Stamina : MonoBehaviour {
 
     public float maxStamina;
     public float currentStamina;
     public float staminaRegen;
     public float sprintDecr;
     public float movement;
     public float sprintSpeed;
     public float runSpeed;
     public bool moving;
     public bool isSprinting;
     public float sprintTest;
     CharacterMovement CC;
     GameObject cube;
 
 
     void Start () {
 
     }
     
     
     void Update () {
         movement = Input.GetAxisRaw("Horizontal") + Input.GetAxisRaw("Vertical");
         MovementCheck();
         SetStaminaMax();
         Sprinting();
         sprintTest = Input.GetAxisRaw("Sprint");
         cube = GameObject.Find("Cube");
         CC = cube.GetComponent<CharacterMovement>();
     }
 
 
     public void MovementCheck()
     {
         if (movement == 0)
         {
             moving = false;
         }
         else
         {
             moving = true;
         }
     }
 
     public void SetStaminaMax()
     {
         if (currentStamina <= 0)
         {
             currentStamina = 0;
         }
         if (currentStamina >= maxStamina)
         {
             currentStamina = maxStamina;
         }
     }
 
     public void Sprinting()
     {
         if (Input.GetAxisRaw("Sprint") > 0 && currentStamina > 0 && !isSprinting && moving)
         {
             CC.Speed = sprintSpeed;
             isSprinting = true;
         }
         else
         {
             CC.Speed = runSpeed;
             isSprinting = false;
         }
     }
 }

I have yet to add a stamina regeneration and stamina decrease but all the values are set in the editor so everything should work.

Comment
Add comment · Show 15
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 Ali-hatem · Apr 19, 2016 at 05:46 PM 0
Share
 if(cube != null){
 CC = cube.GetComponent<Character$$anonymous$$ovement>();
 }else{
      print("eather cube is null or you miss typed it's name");
 }
avatar image Thijsx7 Ali-hatem · Apr 19, 2016 at 05:55 PM 0
Share

I just tried what you said but I still get the same error :/

avatar image Ali-hatem Thijsx7 · Apr 19, 2016 at 06:08 PM 0
Share

so did you get the debug in unity "eather cube is null or you miss typed it's name" & make sure Character$$anonymous$$ovement script attached to cube object & the name of the cube is the same in unity .

Show more comments
Show more comments
avatar image Thijsx7 · Apr 19, 2016 at 07:11 PM 0
Share

I can't reply under the question anymore so I just have to do it here: It is not printing "Something went wrong!" and putting the cube in the slot on my script doesn't work either. I have no idea what to do because I really want to continue.

avatar image Ali-hatem Thijsx7 · Apr 19, 2016 at 09:15 PM 0
Share

ok last try . is the error exactly in thees lines CC.Speed = sprintSpeed; & CC.Speed = runSpeed;if you double click the error in unity because if so you should have error in

  void Update () {
     Sprinting(); // should have error here to 
     }

& in public void Sprinting()

& is the error print @ start of the scene or after if (Input.GetAxisRaw("Sprint") > 0 && currentSta$$anonymous$$a > 0 && !isSprinting && moving) all the parts of this line became true & sorry if i not respond now it's 12 A$$anonymous$$ now .

avatar image Thijsx7 Ali-hatem · Apr 20, 2016 at 06:54 PM 0
Share

The error comes every tick after the game has started and every tick when all the parts of that line become true until they are no longer all true. The first error is in the CC.Speed = runSpeed; and the second error is in the CC.Speed = sprintSpeed;. Unity doesn't say that there are any errors in the Update function and when I check myself I can't really see why that shouldn't work. Sorry for replying late but I had a busy day. Really thanks for trying to help me!

Show more comments
avatar image Thijsx7 · Apr 25, 2016 at 03:28 PM 0
Share

I tried removing the else and it worked! The problem now is that I cannot set the speed back to runSpeed. After some testing I found out that the is something wrong with the movement check: when I replaced the else with if, it only worked when the movement check was not used.

 using UnityEngine;
 using System.Collections;
 
 public class Sta$$anonymous$$a : $$anonymous$$onoBehaviour {
 
     public float maxSta$$anonymous$$a;
     public float currentSta$$anonymous$$a;
     public float sta$$anonymous$$aRegen;
     public float sprintDecr;
     public float movement;
     public float normalSpeed;
     public float sprintSpeed;
     public bool moving;
     public bool isSprinting;
     public float sprintTest;
     Character$$anonymous$$ovement CC;
     public GameObject cube;
 
 
     void Start () {
 
     }
     
     
     void Update () {
         movement = Input.GetAxisRaw("Horizontal") + Input.GetAxisRaw("Vertical");
         $$anonymous$$ovementCheck();
         SetSta$$anonymous$$a$$anonymous$$ax();
         Sprinting();
         sprintTest = Input.GetAxisRaw("Sprint");
         if (cube != null || this.GetComponent<Character$$anonymous$$ovement>() != null)
         {
             CC = cube.GetComponent<Character$$anonymous$$ovement>();
         }
         else
         {
             print("Something went wrong!");
             Debug.Log("Error!");
         }
     }
 
 
     void $$anonymous$$ovementCheck()
     {
         if (movement == 0)
         {
             moving = false;
         }
         if (movement != 0)
         {
             moving = true;
         }
     }
 
     void SetSta$$anonymous$$a$$anonymous$$ax()
     {
         if (currentSta$$anonymous$$a <= 0)
         {
             currentSta$$anonymous$$a = 0;
         }
         if (currentSta$$anonymous$$a >= maxSta$$anonymous$$a)
         {
             currentSta$$anonymous$$a = maxSta$$anonymous$$a;
         }
     }
 
     void Sprinting()
     {
         // the first statement
         if (Input.GetAxisRaw("Sprint") > 0 && currentSta$$anonymous$$a > 0 && movement != 0)
         {
             CC.Speed = sprintSpeed;
             isSprinting = true;
         }
         // the second statement which only works when the movement check is not used (so it doesn't work in this script)
         if (Input.GetAxisRaw("Sprint") == 0 || currentSta$$anonymous$$a <= 0 || movement == 0)
         {
             CC.Speed = normalSpeed;
         }
     }
 }

It also gives an error every frame for the second statement before I press my sprintbutton for the first time. After I just pressed it once, the error stops.

I find it really weird that this is the cause of all the problems. Do you have any idea why this happens?

avatar image Ali-hatem Thijsx7 · Apr 27, 2016 at 09:07 AM 0
Share

just tell me when do you want to sprint & when not & what button Input.GetAxisRaw("Sprint") Represent ?

avatar image Thijsx7 Ali-hatem · Apr 27, 2016 at 12:20 PM 0
Share

Sprinting should make the character move faster and you should be able to use it at any time if you have enough sta$$anonymous$$a. the Input.GetAxisRaw("Sprint") represents the left shift button.

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Ali-hatem · Apr 27, 2016 at 04:38 PM

CharacterMovement script:

 public float v,h; // so we can cheek movement from other script 
 void Update () {
      h = Input.GetAxisRaw("Horizontal");
      v = Input.GetAxisRaw("Vertical");
      Movement = new Vector3(h, 0, v);
      Rigidbody.velocity = Movement * Speed;
  }

Stamina script:

 void Start () {
       if (cube != null){
          CC = cube.GetComponent<CharacterMovement>();// no need to be in Update()
      }
  }
  void Update(){
      MovementCheck();
      SetStaminaMax();
      Sprinting();
  }
  void MovementCheck(){
      if(CC.v == 0 && CC.h == 0){
           moving = false;
      }else if(CC.v != 0 || CC.h != 0){
           moving = true;
      }
  }
 void Sprinting(){
     if(Input.GetButtonDown("Sprint") && moving){ //when holding the button
         if(currentStamina > 0){
               CC.Speed = sprintSpeed;
         }
     }
     else if(Input.GetButtonUp("Sprint")){ // when releasing the button
          CC.Speed = normalSpeed;
     }
 }

so i have imagined that what you want if the shift button is pressed & currentStamina > 0 should sprint but you have to not sprint when releasing the shift button that's why i replaced Input.GetAxisRaw with Input.GetButtonDown & Input.GetButtonUp . if this not exactly what you want just tell me don't hesitate .

Comment
Add comment · Show 2 · 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 Thijsx7 · Apr 29, 2016 at 12:51 PM 1
Share

I did what you said and it works now! I have added a few things and this is what my script looks like now:

 void Sprinting()
     {
         if (Input.GetButton("Sprint") && moving)
         {
             if (currentSta$$anonymous$$a > 0)
             {
                 CC.Speed = sprintSpeed;
                 isSprinting = true;
             }  
         }
 
         if (Input.GetButtonUp("Sprint") || currentSta$$anonymous$$a == 0 || !moving)
         {
             CC.Speed = normalSpeed;
             isSprinting = false;
         }
     }

The reason that I used GetAxisRaw is because I thought that it wasn't possible to use an axis in GetButtonDown. I added the !moving because I don't want the player to be able to sprint into walls while still depleting sta$$anonymous$$a. Thanks for your help! I could not have done it without you!

Greetings!

avatar image Ali-hatem Thijsx7 · Apr 29, 2016 at 03:14 PM 0
Share

finally glad to hear that . & believe me i thought about sta$$anonymous$$a how it's gone decrease during run or other way but how could i know . but nice touch from you & good luck.

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

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Character moving backwards when I press the forward key (w) and moving forward when pressing backwards (s),Character going backwards when pressing the forwards key (w) 1 Answer

Character movement 1 Answer

Character Jump? Alter the Y axis during Vector3.MoveTowards? 1 Answer

Most suitable way to make player move for an open world environment? 0 Answers

my sprint script is toggling? help please! 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