Instantiating random prefabs gives wrong position
Hi, I am making a game, where random obstacles are spawning in an infinite loop as you head downwards. The problem is that as the type of randomly chosen obstacle changes, it spawns too high, or doesn't spawn on my vision at all. Can you figure out what's going on? (7.3f x axis is because prefab is to the left)
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Trigger Reached.");
SpawnType();
}
}
void SpawnType()
{
if(Time.time > reqTime)
{
Type = Random.Range(1, 3);
newType = new Vector2(0, lastType.y - 5);
lastType.y = lastType.y - 5;
if (Type == 1)
{
Debug.Log("Type 1");
newType.x = 7.3f;
Instantiate(Type1, newType, Quaternion.identity);
}
else if (Type == 2)
{
Debug.Log("Type 2");
Instantiate(Type2, newType, Quaternion.identity);
}
reqTime = Time.time + 2;
}
}
Answer by Anne-Pier · Apr 25, 2018 at 09:42 PM
You're not doing newType.x = 7.3f; in the else if statement. Not sure if that's necessary though, anyway does it work if you don't swap between the 2 types?
Answer by tormentoarmagedoom · Apr 26, 2018 at 09:13 AM
Good day.
You can assign the new instantiated object to a GameObject variable, and change its position after instantiating.
GameObject NewObject = Instantiate(Type2);
NewObject.transform.position= PositionYouWant;
...
Now you have the object in the NewObject variable, so can modify all you want like any other gameobject.
If some answer helped, accept the answe and close the question!
Answer by vaxerski · Apr 26, 2018 at 01:35 PM
Okay, I found the problem!
For anyone curious...
The lastType vector2 was stored inside those Obstacles, and therefore it was reset every instantiate.
I fixed it by moving the value over to the player (Bluq), making it static and only referencing to it inside Obstacles.
Bluq: public static Vector2 lastType;
Obstacle:
GameObject thePlayer = GameObject.Find("sprite");
Bluq playerScript = thePlayer.GetComponent<Bluq>();
Bluq.lastType.y -= 5;
Instantiate(Obstacles[Type], Bluq.lastType, Quaternion.identity);
Thanks for your time, everyone who tried to help.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161517im_/https://answers.unity.com/themes/thub/images/avi.jpg)