Instantiate not spawning at correct position
I have a bunch of slots I want to instantiate to form my inventory. Here's my code:
// Generate inventory and quick slots UI
quickSlotPositions = new[] { new Vector3(-605, -605, 0), new Vector3(-500,-605,0), new Vector3(-395,-605,0), new Vector3(-290,-605,0), new Vector3(-185,-605,0), new Vector3(185,-605,0), new Vector3(290,-605,0), new Vector3(395,-605,0), new Vector3(500,-605,0), new Vector3(605,-605,0)};
quickSlotContainer = gameObject.transform.Find("Quick Slot Container").gameObject;
for (int i = 0; i < quickSlotPositions.Length; i++)
{
print(quickSlotPositions[i]);
var newQuickSlot = Instantiate(PrefabManager.Instance.prefabDatabase["Quick Slot"], quickSlotPositions[i], Quaternion.identity, quickSlotContainer.transform);
}
However, all my slots get instantiated at -605, -605, 0 which is the first index of the array. My print statement shows that I'm iterating through the array correctly. What is going wrong? It spawns at my prefab's location, which when set to 0,0,0 spawns it at 0,0,0 instead of my array positions as well.
That code doesn't compile. Did you copy / paste that directly?
I set the parent / prefab as inspector assignments as I didn't have your Prefab$$anonymous$$anager
and I never use anything with Find
in its name. This works fine:
using UnityEngine;
public class QuickSlot : $$anonymous$$onoBehaviour
{
public Transform container;
public Transform prefab;
// Use this for initialization
void Awake()
{
// Generate inventory and quick slots UI
Vector3[] quickSlotPositions = new Vector3[] {
new Vector3(-605, -605, 0),
new Vector3(-500, -605, 0),
new Vector3(-395, -605, 0),
new Vector3(-290, -605, 0),
new Vector3(-185, -605, 0),
new Vector3(185, -605, 0),
new Vector3(290, -605, 0),
new Vector3(395, -605, 0),
new Vector3(500, -605, 0),
new Vector3(605, -605, 0)
};
for (int i = 0; i < quickSlotPositions.Length; i++)
{
print(quickSlotPositions[i]);
var newQuickSlot = Instantiate(this.prefab, quickSlotPositions[i], Quaternion.identity, this.container);
}
}
}
Answer by tormentoarmagedoom · May 15, 2018 at 10:46 AM
Good day.
You can always change the position of the instantiated object after instantiating. As you have stored the instantiated object at newQuickSlot.
newQuickSlot.transform.localpoation = PositionYouWant
Bye!
Your answer
Follow this Question
Related Questions
Transform position of child is way off. 1 Answer
Cannot convert UnitEngine.Vector3 to UnityEngine.Transform when using .postition 1 Answer
How to store a position that is moving to create a prefab to spawn at the exact position 1 Answer
Instantiate prefab if no prefab exists at location 1 Answer
Instantiated prefab has a z-axis of 90 0 Answers