- Home /
How do i Instantiate a prefab with specific assests included
I have a question on how to have a prefab that is instantiated have an assest attached to a script that is in the game world already. So basically the prefab gets spawned in and in one of the scripts it needs a assest to be pointed too but when it spawns it doesnt have the value and i want it to point to a prefab already in the game world how would i go about doing this in c# Thank you
Answer by Kiwasi · Jul 01, 2014 at 07:02 AM
You can build any links you need in Awake() and Start().
Answer by Andres-Fernandez · Jul 01, 2014 at 07:10 AM
I suggest 2 different approaches:
Have the link in the object that spawns the prefab. That way the spawner will have a reference to the spawned object and can set the link from it's own link.
http://docs.unity3d.com/ScriptReference/GameObject.Find.html
Answer by Yokai · Jul 01, 2014 at 07:14 AM
I'm not really sure what you're trying to do.
Are you trying to pass an existing GameObject as a variable for your script? If so I suppose the easiest way would be to look for a correct object in the scene and then set the variable during Start()
or OnEnable()
like so
GameObject go;
void OnEnable()
{
// This attaches the first object of type T found on your scene to the go var
go= GameObject.FindObjectOfType<T>();
}
Or do you want to have your instantiated object be a child of a GameObject on the scene? If so you need to use Transform.parent{set}
:
// You still need a correctly set GameObject var
void OnEnable()
{
transform.parent= go.transform;
// Also set position, rotation and scale to new parent
transform.position= Vector3.zero;
transform.rotation= Quaternion.identity;
transform.localScale= Vector3.zero;
}
Your answer
Follow this Question
Related Questions
Issue Instantiating prefab in C# 2 Answers
Destroying Objects. 1 Answer
C# Instantiating a Gameobject with a Flat Sphere Collider 1 Answer
Null Reference Exception on instantiated object's script. 2 Answers
,Instantiating Prefab in C# 0 Answers