Search code examples
c#unity-game-enginez-indexinstantiation

Set z transform position of an instantiated GameObject sprite in unity


Is there an easy (shorter) way to set the z transform position of an instantiated game object (sprite) in unity? I want to set each instance to 2 for now. Here's the one line of code I am using, I just wanted to set the z position and it seems cumbersome to do it this way - ignore the first line as I am only including it to demonstrate how the GameObject has been instantiated:

GameObject laser = Instantiate(laserPrefab, transform.position, Quaternion.identity) as GameObject;
laser.transform.position = new Vector3(laser.transform.position.x, laser.transform.position.y, 2);

Thanks in advance!


Solution

  • There is no simpler way of doing this, but you can create method to make your code assigning new position shorter. For example, creating method like this:

    Vector3 SetZ(Vector3 vector, float z)
    {
        vector.z = z;
        return vector;
    } 
    

    Would let you to set new object's position like this

    laser.transform.position = SetZ(laser.transform.position, 2);
    

    You have to use method, because trying to do it directly, using property would result in compile time error.

    transform.position.z = 2;
    

    Results in error: CS1612: Cannot modify the return value of 'Transform.position' because it is not a variable