How to reference prefabs before instantiation?

Hello everyone!

I have a script in which I need to reference a prefab GameObject called BallFloating. This prefab GameObject (BallFloating) doesn’t instantiate until 10 seconds after run time begins. At 10 seconds it instantiates in the scene as BallFloating(Clone). Based on what I know so far (which is not much), the Find method is typically placed in Start which executes once at the beginning of run time. How can I Find and reference BallFloating or BallFloating(Clone) if it hasn’t been instantiated yet?

Here is my script:

using UnityEngine;
using System.Collections;

public class SetRightVelocityBall : MonoBehaviour
{

    private BoolKeeper _refBoolKeeper;
    private GameObject _refBall;

    void Start ()
    {
        _refBoolKeeper = GameObject.Find("BoolKeeper").GetComponent<BoolKeeper>();
        _refBall = GameObject.Find ("BallFloating(Clone)");
    }
   
    void Update ()
    {
        if (_refBoolKeeper.rightRacketCollision == true)
        {
            Debug.Log ("GOT IT!");
            //do something to _refBall
        }
    }
}

There are 2 super easy methods:

  • First is loading the reference from the resources folder. You MUST have a folder named “Resources” in your Assets folder for this to work, but you can have other folders inside your resources folder. Unity - Scripting API: Resources.Load

  • Second method is making a public or serialized GameObject in a component, then click-and-drag your prefab from your assets folder into the empty spot in the inspector for that component.

1 Like

Try these steps

void Start ()
    {
        _refBoolKeeper = GameObject.Find("BoolKeeper").GetComponent<BoolKeeper>();
         Invoke("After_Ten_sec", 11.0f);//Invoke a method after 11 seconds
    }

void After_Ten_sec()
{
        //till these time you must have instantiated BallFloating
        _refBall = GameObject.Find ("BallFloating(Clone)");
}
1 Like

I went with the second method. Thanks so much!

This would work too. Thanks.