- Home /
Instantiate Object At Local Position
This question is kind of continued from this one: https://answers.unity.com/questions/380829/instantiating-a-prefab-at-local-position.html
I can instantiate an object to local space and it works with the following code:
private void AddGoalStalker()
{
GameObject goalStalker = Instantiate(goalStalkerPrefab, hazardDirectory, false) as GameObject;
Vector3 pos = new Vector3(hole.transform.position.x, goalStalker.transform.position.y, hole.transform.position.z);
goalStalker.transform.position = pos
}
However, the below code doesn't work even though it's essentially doing the same thing?
private void AddGoalStalker()
{
Vector3 pos = new Vector3(hole.transform.position.x, goalStalkerPrefab.transform.position.y, hole.transform.position.z);
InstantiateObject(goalStalkerPrefab, hazardType.GoalStalker, pos);
}
private void InstantiateObject(GameObject prefab, Hazard hazard, Vector3 pos)
{
GameObject obj = Instantiate(prefab, hazardDirectory, false) as GameObject;
float rot = RandomRot(hazard);
obj.transform.position = new Vector3(pos.x, pos.y, pos.z);
obj.transform.Rotate(Vector3.up, rot, Space.Self);
}
Does anyone know why this doesn't work? I need to do it the second way for additional checks in the InstantiateObject() method that won't affect the positioning.
Any help will be really appreciated
Answer by unity_ek98vnTRplGj8Q · Oct 21, 2020 at 03:34 PM
goalStalkerPrefab.transform.position is not the same as goalStalker.transform.position. Try changing the line where you set the position to obj.transform.position = new Vector3(pos.x, obj.transform.position.y, pos.z);
.
goalStalkerPrefab looks at the actual prefab object (probably has a y value of 0), while goalStalker.transform.position is looking at the copy of the prefab that you have spawned in your scene which (I believe) will have the same Y value as your "hazardDirectory" since you are spawning it as a child of that.
Answer by jdaviee · Oct 21, 2020 at 03:36 PM
Thanks for the help @unity_ek98vnTRplGj8Q , the changes worked! Below is the new, working code :)
private void AddGoalStalker()
{
Vector3 pos = new Vector3(hole.transform.position.x, goalStalkerPrefab.transform.position.y, hole.transform.position.z);
InstantiateObject(goalStalkerPrefab, hazardType.GoalStalker, pos);
}
private void InstantiateObject(GameObject prefab, Hazard hazard, Vector3 pos)
{
GameObject obj = Instantiate(prefab, hazardDirectory, false) as GameObject;
float rot = RandomRot(hazard);
obj.transform.position = hazardDirectory.position + pos;
obj.transform.Rotate(Vector3.up, rot, Space.Self);
}
Your answer
Follow this Question
Related Questions
Explosion at mouse 1 Answer
GameObject position and localPosition not changing in hiearchy, only in script. 0 Answers
How use local position of prefab for my instantiate ? 1 Answer
Collider.bounds position is wrong? 3 Answers
Changing localPosition gives no error, but doesnt change prefab localPosition 0 Answers