Home > Software design >  Duplicating and moving an object by a certain amount in Unity3D
Duplicating and moving an object by a certain amount in Unity3D

Time:05-30

I want to duplicate an object by a certain (integer) amount and move it by that x-0.2 (so the first one would be -0.2, second would be -0.4, third would be -0.6). When I try to do this I get the error "Cannot modify the return value of 'Transform.position' because it is not a variable". My code:

public GameObject object;

// Start is called before the first frame update
void Awake()
{
    GameObject[] clones = null;
    for (int i = 0; i < GameManager.singleton.currentLevel; i  )
    {
        clones[i] = GameObject.Instantiate(object);
        clones[i].transform.position.y = -0.2 * (i   1);
    }
}

Thanks in advance!

CodePudding user response:

You can use Transform.translate to move the clone. The docs for this can be found here: https://docs.unity3d.com/ScriptReference/Space.World.html

You could also set the transform.position to a new vector3 like in this example: https://docs.unity3d.com/ScriptReference/Transform-position.html

You get this error because you cannot directly set the x, y and z values of transform.position (I believe that they are read only) but you can set transform.position to a new vector3

This may also help to explain it: https://answers.unity.com/questions/656129/c-changing-the-x-and-y-values-of-a-gameobject.html

CodePudding user response:

Entering a null value in a variable does not define an array. In this case you have no array to configure its members. object itself is also a reserved word in C# and you can not use it as a variable name. To solve the problem, change the code as below.

public GameObject obj;

void Awake()
{
    var clones = new GameObject[GameManager.singleton.currentLevel];
    for (int i = 0; i < clones.Length; i  )
    {
        clones[i] = GameObject.Instantiate(obj);

        var pos = clones[i].transform.position;
        pos.y = -0.2f * (i   1);
        clones[i].transform.position = pos;
    }
}
  • Related