- Home /
Creating new Transform from existing objects Transform to Instantiate object
I've got an Empty game object that will be an object spawner, but I need the objects that spawn to vary slightly along the x-axis some, to then instantiate. Using the code below, I've got it's random position moving just fine using Random.Range, but it's shifting the Empty game object with this script on it each time it instantiates an object, rather than instantiating the object at the different transform after changing it's position in relations to the spawner.
private Transform newSpawnTransform;
void Start ()
{
newSpawnTransform = transform;
}
void randomForce()
{
newSpawnTransform.position += new Vector3 ((Random.Range (-.1f, .1f)), 0f, 0f);
}
Then I'm Calling the randomForce function, and instantiating the object when needed.
randomForce ();
Instantiate (object, newSpawnTransform);
Perhaps I just need clarification on how the transforms work, since it moves the parent object to instantiate the objects, rather than use the parent transform, then instantiate it nearby. I also looked at this question on how to instantiate objects without becoming a child in hopes of changing where it spawns, but couldn't get it to work. https://answers.unity.com/questions/1401222/instantiate-an-object-without-being-the-child-of-a.html
Answer by Shameness · Jul 02, 2018 at 04:55 PM
See the Instantiate reference, there is more than one constructor: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html .
One you are using is:
public static Object Instantiate(Object original, Transform parent); .
I suggest you to use one with in the first example in the previous doc link.
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
Answer your case:
Instantiate (object, newTransform.position, Quaternion.identity);
Thank you for the quick help. I understand that adding .position and Quaternion.identity makes the instantiated objects not children, but it doesn't solve my main problem of why this newTransform is moving the whole gameobject to spawn other objects, rather than using that position to spawn objects separate from where the spawner is.
Changing position of the parent object affects children as well. Your newSpawnTransform holds same reference (or pointer) with original transform of the empty game object.
I see, so what would I need to do to change the reference? Would I be able to set each of the newTransform positions separate, rather than setting it by setting it equal to transform? The objects instantiated are no longer spawning as children, so I'm not sure what you mean with "Changing position of the parent object affects children as well"