Search Unity

Need some help with GetComponent<>();

Discussion in 'Scripting' started by sjameselvis, Oct 19, 2019.

  1. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    Hello guys,

    I know that there are many Threads on this topic but they don't seem to help me...
    I am trying to modify a variable from another script and I am not doing it right... what is wrong in my code?
    Code (CSharp):
    1. public GameObject Bow; //the GameObject with the BowScript component
    2. BowScript BowS;
    3.  
    4. void Start()
    5. {
    6.     BowScript BowS = Bow.GetComponent<BowScript>();
    7. }
    8. void Update()
    9. {
    10.     if (Input.GetKey("+"))
    11.     {
    12.         BowS.FireSpeed += 20;
    13.     }
    14. {
     
  2. What's the effect you're seeing? Have you drag and drop the "game object with the Bow script on it" into the slot in the inspector? Does the game object have the BowScript on it?

    BTW, if you don't need the Bow game object for anything other than this, you can simplify this just like this:
    Code (CSharp):
    1. public BowScript BowS;
    And then just drag and drop the same game object. The BowS will contain the component reference automatically.
     
  3. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    First of all, you dont use "Bow" for anything other than getting its BowScript component, so you could just change the type of Bow to BowScript, which will directly assign this component instead of the GameObject.
    Secondly: what's wrong? Is there an error? I dont know what your BowScript does, but what you are doing seems fine at first glance.

    A few notes on code quality:
    Most C# programmers name their variables using camelCase, starting with a lower case letter and chaining each new word starting with a capital letter. Methods, properties and classes would do the same but start with an upper case letter, resulting in UpperCamelCase. This is called a naming convention, and makes it easier to grasp what things are in your code. It also makes it more compatible with code of other programmers and the Unity API itself.
     
  4. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    I am getting this error:
    Object reference not set to an instance of an object(line 12)
     
  5. ?

    I don't see the value in confusing newbies with code formatting problems. They should first learn the logic then they have time to learn the formatting of their code.
     
  6. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    yes... I did


    I actually know these "rules" but while I was trying to debug I renamed these variables multiple times and that's why they are all upper case
     
  7. Could you please post your BowScript as well?
    Also put a
    - Debug.Log(Bow) before the 6th line
    - Debug.Log(BowS) after the 6th line
    - Debug.Log(BowS) before the 12th line
    and tell us the results.
     
  8. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    This is the full surce code..
    Logs are in the image.

    Code (CSharp):
    1.  
    2. using UnityEngine.SceneManagement;
    3. using UnityEngine;
    4. public class GameController : MonoBehaviour
    5. {
    6.     private bool devToolsActivated = false;
    7.     public GameObject bow;
    8.     BowScript bowS;
    9.     void Start()
    10.     {
    11.         BowScript bowS = bow.GetComponent<BowScript>();
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         if (Input.GetKeyDown("q"))
    18.         {
    19.             devToolsActivated = !devToolsActivated;
    20.         }
    21.         if (devToolsActivated)
    22.         {
    23.             Debug.Log("devTools are active");
    24.             if (Input.GetKeyDown("="))
    25.             {
    26.                 bowS.fireSpeed -= 20;
    27.                 Debug.Log("More FireSpeed");
    28.             }
    29.             if (Input.GetKeyDown("-"))
    30.             {
    31.                 bowS.fireSpeed += 20;
    32.                 Debug.Log("Less FireSpeed");
    33.             }
    34.         }
    35.         else
    36.         {
    37.             Debug.Log("devTools are not active");
    38.         }
    39.  
    40.         if (Input.GetKey("r"))
    41.         {
    42.             SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    43.         }
    44.     }
    45. }
    46.  
    Variable I am trying to change: (in script BowScript)
    Code (CSharp):
    1. public float fireSpeed = 80.0f;
    upload_2019-10-19_22-11-3.png


    And yes, I did assign the Bow variable.
     

    Attached Files:

  9. I don't understand why are you reluctant to share your things here, when we're trying to help, we need to pull every bit of information out of you like a tooth. And even when you do you hide important bits. Like full screen inspector? Eh. Whatever.

    Are you sure the "Bow" object in that "Bow" variable is a GameObject and not a Prefab from the project?
    And are you sure it has the BowScript component on it?

    Because you failed to do what I have asked from you to put Debug.Log at strategic places to find out what is null...
     
  10. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    I don't like to share the whole script because I usually write stupid things...

    Bow actually was a prefab. After unpacking it completely I still get the same error.

    Well sorry for that.. I've seen your answer after posting mine. So here is what you've asked for..(this is my start function)
    Code (CSharp):
    1. void Start()
    2.     {
    3.         BowScript bowS = bow.GetComponent<BowScript>();
    4.         Debug.Log(bow);
    5.         Debug.Log(bowS);
    6.     }
    upload_2019-10-19_22-39-2.png
    BTW.. I get the errors when I press "-" or "="
     
  11. Please don't care about that. We do stupid things all the time, believe me. This is just part of the development. Especially during the hard core coding there are things which needs to be refactored later. Don't be shy, share and it's easier to help you.

    So, what you need to do is to change this
    Code (CSharp):
    1. BowScript bowS = bow.GetComponent<BowScript>();
    to this
    Code (CSharp):
    1. bowS = bow.GetComponent<BowScript>();
    See? Even we didn't spot it for first.
     
    sjameselvis likes this.
  12. Deleted User

    Deleted User

    Guest

    Don't worry, we've read everything yet... :D Including from me!
     
    Lurking-Ninja likes this.
  13. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,157
    Scope. It's very important to understand that there are different levels of scope for a variable. You have global scope, method scope, and block scope. Global is overridden by method and method is overridden by block.

    Here you are defining a global variable named BowS.
    Code (csharp):
    1. public GameObject Bow; //the GameObject with the BowScript component
    2. BowScript BowS;
    Here lies the actual problem. You intended to access the global variable named "BowS", but you made the mistake of trying to define it a second time and that creates a method variable that overrides the global one.
    Code (csharp):
    1. void Start()
    2. {
    3.     BowScript BowS = Bow.GetComponent<BowScript>();
    4. }
    Here you are once again attempting to access the global variable, but since you retrieved the component and stored it in the method variable of the Start() method the global variable doesn't actually refer to the component.
    Code (csharp):
    1. void Update()
    2. {
    3.     if (Input.GetKey("+"))
    4.     {
    5.         BowS.FireSpeed += 20;
    6.     }
    7. {
    Finally there is one last problem with this script. You don't have a closing brace at the end of Update() but rather an opening brace. I'm guessing this is just the result of copying the script and forgetting to copy the closing so you just added one and accidentally choose the wrong one.
     
  14. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    Okay guys, I will try to to share more of my code in the future.

    I removed the "BowScript" and it is finally working! Thank you so much! You saved my day =)))
     
    Lurking-Ninja likes this.
  15. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    If you would modify what is wrong, it would help me more.:)


    Idk what you mean with this... which line?
     
  16. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,157
    Last one. You need a "}" at the end of a method to close it out but you have a "{".
     
  17. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    I respectfully disagree. Naming conventions are there to make code uniform, but also easier to read and thus understand. Knowing about conventions is never a bad thing, and i'm personally not a big fan of learning bad habits and then having to get rid of them later. When people feel like they would get confused by it, they can always just ignore it. However, at the very least then they know that conventions exist and can come back to it later.
    Our experiences on this may differ, but so far i've only had (at least a douzen) people who were glad i mentioned it, since they simply did not know about naming conventions. So they wrote the code they did, not because doing it otherwise would confuse them, but simply because they did not know any better. And seeing how a lot of coding tutorials skip naming conventions, this is just something that can easily be missed as a beginner.

    That's my take on the topic. Just thought you may be interrested in another perspective, but feel free to disagree :)
     
    Lurking-Ninja likes this.
  18. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    I agree. In my last Thread I did not know about it and then you told me how to do it right and I appreciated it. I always want to get better. It may be confusing for some, but it is good to format the code because it will be easier to come later and edit something and it just looks better if you ask me :)
     
    Yoreki likes this.
  19. sjameselvis

    sjameselvis

    Joined:
    Aug 28, 2019
    Posts:
    50
    Oh, I see. You mean in the very first post. Yes you are right, I picked the wrong one after copy-pasting the thread, but I had it right in the script.