- Home /
How can I reference in a prefab's script a gameObject found in the scene
Apparently it lets me only reference other prefabs, but I am instantiating(don't know if i'm using the word correctly, i'm referring to making gameObjects out of the prefab, like so ):
bullet = (GameObject)Instantiate (Resources.Load("Projectile"));
Is there a way to specify in the same code the parameter( it isn't really a parameter, it is the public variable whose value we have to define), for a specified instance of the prefab, something like this ?
bullet.shoot.target = X;
In this example, shoot is the script attached to the prefab that bullet is an instance of, target is the public variable inside the shoot script, x is the name of the gameObject that we would use as a public variable in the script. The second part of the question is if there is a way of getting a list of all the gameObjects from a scene, being able to select which one you want by tags or by name, like so:
bullet.shoot.target = MainScene.getGameObject("Target");
Answer by Em3rgency · Jun 23, 2013 at 06:52 PM
//You can find object by name and access the public functions and/or variables like this:
GameObject myObject = GameObject.Find("ObjectName");
myObject.GetComponent<scriptName>().function();
//For a tag search
GameObject player = GameObject.FindWithTag("Player");
player.GetComponent<OtherScript>().DoSomething();
http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html The script reference page is an awesome place ;)
Thanks for the response. Looking back, the way I worded my concern yielded me no results. Regardless, thanks a lot, that is exactly what I needed!
I suggest using the script reference page. It has an awesome search function, where you type in a keyword and it spits out all methods with that word. Searching for "GameObject" would've even found you that function :)
This is the only way you can do it with Resources Load. If you stored a reference to your projectile prefab and instantiated that, you could typecast and instantiate straight away as a script, then access its variables without GetComponent :
public ProjectileScript projectile; // drop your prefab in the inspector here
private ProjectileScript bullet;
void SomeFunction()
{
bullet = Instantiate( projectile, transform.position, Quaternion.identity );
bullet.shoot.target = X;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613104740im_/https://answers.unity.com/themes/thub/images/avi.jpg)