Search Unity

Help - get variable with GetComponent error

Discussion in 'Scripting' started by quantum_rez, Nov 16, 2012.

  1. quantum_rez

    quantum_rez

    Joined:
    Oct 23, 2012
    Posts:
    35
    Hi guys, i need some help here.

    i want to get variable from another scene, but there's some error and i don't understand the error.

    i have "sceneCity with scriptCity" and "sceneShop with scriptShop".

    in sceneCity i drag "gameObject with scriptShop" to " var sceneShop in sceneCity inspector".

    this is the step what variable i want to get :
    1. when i click on shop button in sceneCity, i will move to sceneShop.
    2. in sceneShop, when i click cube button, my variable isCube become true and i will back into sceneCity.
    3. in sceneCity, i will print variable isCube after i click buy button at sceneShop

    This is the error :
    NullReferenceException: Object reference not set to an instance of an object
    scriptCity.Start () (at Assets/scriptCity.js:42)


    This is my script for sceneCity :
    Code (csharp):
    1. var sceneShop : scriptShop;
    2.  
    3. var isCube : boolean;
    4.  
    5. function Start () {
    6.     sceneShop = gameObject.GetComponent(scriptShop);
    7. isCube = sceneShop.isCube;
    8.     print(isCube);
    9. }
    10.  
    11. function OnGUI () {
    12. if(GUI.Button(Rect(Screen.width / 2 + 220, Screen.height / 2 + 165, 50, 30),"Shop")){
    13.         Application.LoadLevel("sceneShop");
    14.     }
    15. }
    16.  
    17.  

    This is my script for sceneShop :
    Code (csharp):
    1.  
    2. var isCube : boolean = false;
    3. function OnGUI () {
    4. if(GUI.Button(Rect(Screen.width / 2 - 100, Screen.height / 2 + 30, 50, 25),"Cube")){
    5.         isCube = true;
    6.         Application.LoadLevel("sceneCity");
    7.     }
    8. }
    Hope you guys will help me.

    Thanks :D
     
    Last edited: Nov 16, 2012
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    So - a few things here.

    1- The error message you posted says the error is occurring in scriptCity.js which you did not post any code from.
    2- If sceneCity has a public variable that you would presumably set via the Inspector then why are you setting it in Start()?
    3- Your variable names are terrible. You have a variable named sceneShop which is actually of type scriptShop. sceneShop is also a type in and of itself so it becomes confusing rather quickly.
     
  3. quantum_rez

    quantum_rez

    Joined:
    Oct 23, 2012
    Posts:
    35
    hahaha, sorry it's my fault if you confused to see my code. But thanks for your input, i'll change my code so it's can be much better :D

    and i already solved this problem, there's someting i miss and wrong with my code and my step.

    Thanks :D