Search Unity

My Object will not be found!?

Discussion in 'Scripting' started by Andreas12345, Jul 19, 2019.

  1. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    375
    I have
    Code (CSharp):
    1. public RPS_Storage storageScript;
    2.  
    3.   // Start is called before the first frame update
    4.     void Start()
    5.     {
    6.  
    7.  
    8.         RPS_Storage storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();
    But the field is empty, also when i try to:
    Code (CSharp):
    1. void Update()
    2.     {
    3.        if (storageScript == null)
    4.         {
    5.             storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();
    6.         }
    7.     }
    where is the error?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,662
    The error is you have declared a public class variable named storageScript.

    But then in start, you declare a local variable named storageScript. These are not the same variables.

    Code (CSharp):
    1. storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();
    Now if Update is also returning null, then you need to verify your gameObject name and that it has the right component on it.
     
  3. APSchmidt

    APSchmidt

    Joined:
    Aug 8, 2016
    Posts:
    2,426
    First error, using GameObject.Find in Update!

    Then, do not use GameObject.Find, set your object as a public variable and assign it in the Inspector instead. :)
     
    StarManta likes this.
  4. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    375
    I need to do it in Runtime
     
  5. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    375
    So i need to :
    Code (CSharp):
    1. void Update()
    2.     {
    3.        if (storageScript == null)
    4.         {
    5.             RPS_Storage storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();
    6.          
    7.         }
    8.     }
    ?
     
  6. WallaceT_MFM

    WallaceT_MFM

    Joined:
    Sep 25, 2017
    Posts:
    264
    No, you see how you've typed 'RPS_Storage storageScript' in Update? That creates a new variable that will disappear at the end of update.
     
  7. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    375
    Is not allowed: upload_2019-7-19_17-58-30.png
     
  8. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    4,662
    I'm not sure if you actually looked at what I typed or if you just didn't understand it. Your line in Start is incorrect and I gave you the correct line.
     
    Andreas12345 likes this.
  9. Andreas12345

    Andreas12345

    Joined:
    Oct 17, 2013
    Posts:
    375
    Oooops got it :) Thanks