Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 ModernArtery · May 01, 2015 at 11:58 PM · beginnernullreferenceexceptioninitializationassignment

Assignment working in Update() but not in Start()?

I'm trying to access my Player object's Rigidbody2D so I can set its velocity based on controller input. To do this, I was assigning the Rigidbody2D to a variable "playerRB", using the following line of code:

 Rigidbody2D playerRB = this.gameObject.GetComponent<Rigidbody2D> ();

After some trial and error, I found that my approach works just fine but only if I place that assignment statement in the Update() function. I'd rather place it in the Start() function, because wouldn't that be more efficient? As I understand it, it shouldn't need to reassign that value every frame, and doing so is just wasting CPU time. Maybe I'm wrong, though, and that assignment does need to happen every frame.

Is it not working in Start() because the object isn't yet initialized so trying to access the GameObject at that point doesn't work? If so, can I create a separate function to handle the assignment of playerRB, and set that function to run only once immediately after the object is initialized?

Full code below. Note that the code pasted below is working as intended, I just want to know if it's possible to move the assignment of playerRB from Update() to Start() to be more efficient. I'm new to this, so any other comments, criticisms, suggestions or improvements are also welcome.

 using UnityEngine;
 using System.Collections;
 
 public class PlayerController : MonoBehaviour {
 
     public float Speed = 1.0f;
     float velx = 0.0f;
     float vely = 0.0f;
     public PlayerProjectile weapon;
     Rigidbody2D playerRB;
 
     // Use this for initialization
     void Start () 
     {
         //The line below doesn't work when placed here in Start(), but it works when it's placed in Update ().
         //Rigidbody2D playerRB = this.gameObject.GetComponent<Rigidbody2D> ();
     
     }
     
     // Update is called once per frame
     void Update () 
     {    
         //The line below works when placed in Update(), but I'd prefer not to call it every frame.
         Rigidbody2D playerRB = this.gameObject.GetComponent<Rigidbody2D> ();
         ControllerInput ();
         Vector2 movement = new Vector2 (velx, vely);
         if (playerRB == null) 
         {
             Debug.Log ("playerRB is null!");
         }
 
         playerRB.velocity = (movement * Time.deltaTime * Speed);
     }
     void ControllerInput()
     {
         velx = Input.GetAxis ("LeftStick_X");
         vely = Input.GetAxis ("LeftStick_Y");
         if (Input.GetButtonDown ("Y"))
             {
             weapon = Resources.Load<PlayerProjectile>("Prefabs/Weapons/FastZombieCannon");
             }
         if (Input.GetAxis ("RightTrigger") >= 0.5f) 
         {
             Fire();
         }
     }
 
     void Fire()
     {    
         float playerDirection = Mathf.Atan2 (Input.GetAxis ("RightStick_Y"), Input.GetAxis ("RightStick_X"));
         PlayerProjectile playerProj = Instantiate (weapon, new Vector3 (this.gameObject.transform.position.x + (   Mathf.Cos (playerDirection)  * 1.0f     ), this.gameObject.transform.position.y + (     Mathf.Sin (playerDirection)  * 1.0f     ), 0), Quaternion.identity) as PlayerProjectile;
         //playerProj.transform.rotation = Quaternion.Euler (playerDirection, 0, 0);
         Rigidbody2D projRB = playerProj.gameObject.GetComponent<Rigidbody2D> ();
         if (projRB == null) 
         {
             Debug.Log ("playerProj Rigidbody2D not found!");
         }
         
         projRB.velocity = new Vector2 (  (   Mathf.Cos (playerDirection)  * playerProj.ProjectileSpeed   ) , (     Mathf.Sin (playerDirection)  * playerProj.ProjectileSpeed     ));
     } 
 
 }

Comment
Add comment
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

1 Reply

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

Answer by DoTA_KAMIKADzE · May 02, 2015 at 12:01 AM

It doesn't work because you make a variable inside that function with name of your script's variable instead of assigning the returned value to it. Basically just change this:

 Rigidbody2D playerRB = this.gameObject.GetComponent<Rigidbody2D>();

to this:

 playerRB = GetComponent<Rigidbody2D>();

Also as you probably noticed above^ you don't need to explicitly say this.gameObject.

P.S. Also if your Rigidbody2D component is there before your script is enabled you can get it on Awake:

 private void Awake()
 {
     playerRB = GetComponent<Rigidbody2D>();
 }

You can read the difference between Awake and Start by pressing those links or for even better understanding visit Lifecycle page.

Comment
Add comment · Show 1 · 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 ModernArtery · May 04, 2015 at 09:23 PM 0
Share

This worked perfectly, thanks a ton! The difference between "assigning a value to the existing variable" and "creating a new local variable with the same name" would never have occurred to me. Scope is one of those things that is still hard for me to fully wrap my head around, but now that you point it out it makes perfect sense.

Your answer has actually helped me reach an "Aha!" moment on a couple other issues I've been working on as well. (I get the feeling that happens a lot in program$$anonymous$$g =p)

Thanks again!

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

Base class variables not initialized for sub class? 1 Answer

NullReferenceException even though I assigned it? 1 Answer

Initialize UnityEvent via script 1 Answer

NullReferenceException on an assignment line 0 Answers

Initialising List array for use in a custom Editor 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