Transforming Instantiated Prefabs

Hey all,

What I’m trying to do is write a script for an empty game object called “Tree Randomizer” that selects a prefab at random from four tree objects I’ve created and instantiates a copy of the prefab at the location of each Tree Randomizer object. I also want to flip the image in the y direction once instantiated. In the public array of game objects, I’ve dragged-and-dropped four prefabs of tree objects into the inspector array list.

Instead, what is happening is the transform and rotation values of the prefabs are being changed in the inspector. I don’t understand why this is happening. Also, I have the “X” rotations of the prefabs set to “-15” and for some reason they are being changed to positive “15”. I have no idea why this transform value is being effected at all.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeScript : MonoBehaviour
{
    public GameObject[] trees;
    void Start ()
    {
        Vector3 location = transform.position;
        GameObject tree = trees[Random.Range(0, trees.Length)];
        Instantiate(tree);
        tree.transform.position = location;
        tree.transform.Rotate(new Vector3(0, 180, 0));
    }
}

Well, you are changing the rotation and the position of the instantiated trees in the script, rotating the tree by 180 might be why its showing as positive 15, perhaps dont rotate the tree?

No, he’s rotating the prefab not the copy of the prefab.

Instantiate returns the copy to you.

var newTree = Instantiate(tree);
newTree.transform.position = ......;

There’s also an overload that takes a position and rotation so you could set it all in one line

var newTree = Instantiate(tree, new Vector3(...), location);

Ah, I see. So my “tree” game object is actually the prefab itself, whereas a copy of the prefab has to be declared as a var when instantiating. That seems to have fixed my problem. Also, I believe I was having some weird issues with rotation because I was using Quaternion when I thought I was using Euler. Here’s the new code that is working for anyone having similar problems:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeScript : MonoBehaviour
{
    public GameObject[] trees;

    void Start ()
    {
        Vector3 location = transform.position;
        GameObject tree = trees[Random.Range(0, trees.Length)];
        //Instantiate(tree);
        var newTree = Instantiate(tree);
        newTree.transform.position = location;
        newTree.transform.eulerAngles = (new Vector3(-15, 180, 0));
    }
}

In one line just for funsies :slight_smile:

Instantiate(trees[Random.Range(0, trees.length)], transform.position, Quaternion.Euler(-15, 180, 0));

Yes, thank you!

You saved me bro. Thankyou a million