My Object will not be found!?

I have

public RPS_Storage storageScript;

  // Start is called before the first frame update
    void Start()
    {


        RPS_Storage storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();

But the field is empty, also when i try to:

void Update()
    {
       if (storageScript == null)
        {
            storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();
        }
    }

where is the error?

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.

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.

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. :slight_smile:

1 Like

I need to do it in Runtime

So i need to :

void Update()
    {
       if (storageScript == null)
        {
            RPS_Storage storageScript = GameObject.Find("RPS_Storage").GetComponent<RPS_Storage>();
          
        }
    }

?

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.

Is not allowed: 4764785--453059--upload_2019-7-19_17-58-30.png

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.

1 Like

Oooops got it :slight_smile: Thanks