- Home /
Make prefab appear at start/awake
Hi
I created a prefab and i'm trying to make it appear when the game starts, here is the code i tried:
public GameObject ballPrefab;
Vector2 startPosition;
void Start ()
{
startPosition = new Vector2(4,1);
Instantiate(ballPrefab, startPosition, transform.rotation) ;
}
I also assigned a prefab in the inspector, but it never appears unless i drag it into the Hierarchy window. Please, help !
Answer by Kiwasi · May 13, 2014 at 09:56 PM
Code to be executed must be attached to a GameObject actually in the scene. Code on prefabs in the asset folder will not run unless an instance of the prefab is created in the scene. For your purposes I would suggest an empty GameObject with this script attached.
Thank You, this actually helped. I forgot to add a separate GameObject to the Hierarchy. But no problem with the use of Vector2.
Answer by SkaredCreations · May 13, 2014 at 09:48 PM
This code just works as intended (well, startPosition should be Vector3 not Vector2, but anyway it's automatically casting Vector2 to Vector3 with the Z set to 0). Are you sure that the script is enabled on the gameobject where you attached it in the scene?
Huh. I didn't realise you could implicitly cast a Vector2 to a Vector3. Learn something everyday.
Your answer
Follow this Question
Related Questions
Checking if object intersects? 1 Answer
snake game tail problems 0 Answers
Changing LocalScale in code affecting prefab stored in Assets 1 Answer
Local vs. Global movement 5 Answers
Instantiate a prefab vs create one dynamically at runtime? 1 Answer