- Home /
Object not Instantiating Correctly
Hi there,
I'm trying to instantiate an object relative to a prefab's position. So within the script attached to the prefab, I setup the function below. Problem is that the instantiated prefab is not being instantiated at the right position.
I've used a similar script for another prefab and it's working fine. Anyone have any idea why this is the case?
void CreateEnemySpeech()
{
//instantiate speech
GameObject instEnemySpeech = Instantiate (EnemySpeech, new Vector3(transform.localPosition.x, transform.position.y+200, transform.localPosition.z), transform.rotation) as GameObject;
instEnemySpeech.transform.SetParent (BattleCanvas, false);
EnemySpeechText = EnemySpeech.GetComponent<EnemySpeechContainer> ();
EnemySpeechText.EnemySpeech.text = "text";
Destroy (instEnemySpeech, 4f);
}
Answer by tormentoarmagedoom · Mar 13, 2018 at 11:22 AM
Good day.
I reccomend you to replace this
instEnemySpeech.transform.SetParent (BattleCanvas, false);
for this:
instEnemySpeech.transform.SetParent(BattleCanvas);
and if the position where it apears is not the correctone,m change it via scripitng
instEnemySpeech.transform.position = WhereYouWantPosition ;
Making an object parent/child of another sometimes is complex, becoause if parents have diferent scales and rotations is hard to think each time which should be the correctones... For my experience, is better to first become child/parent, and then move/rotate/scale the objects
If helped, accept the answer! :D
Bye :D
You are right. The object should be instantiating wit respect to his parent so, make your object free and then instantiate. No need to set position after instantiating gameobjct on given position as
instEnemySpeech.transform.SetParent(BattleCanvas);
I recommend use this way of instantiating.
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
For more information visit unity documentation of instantiating https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Hey there, thanks for that!
I tried it out, but doesn't seem to work. However, it seems like the issue may be because the prefab has a recttransform property on it and I read that recttransform doesn't work the same as transform.
Any idea how to instantiate a recttransform at a location?
Thanks!
You should use anchoredPosition to set the position of UI, not transform.position in case of recttransform.
Read The Documentation : https://docs.unity3d.com/ScriptReference/RectTransform-anchoredPosition.html