Transform Translate On Other Objects

Hello guys,

Hope everything is going well with you all?

I have this slight problem with transform translate. I want to move an object that I instantiate from another object. Basically, its a laser that a ship fires. I can get it to instantiate perfect, but moving it seems a problem.

I have noticed that you can use gameobject.transform.Translate() on the primary gameObject - i.e. the ship - but when the laser is created, because it has a different variable and instead reads Weapon[0].transform.Translate() it won’t work. Here is my code. I have cut the code down so it is easier to read.

LaserSpeed  = 5.00f;
private void Awake()
    {
        for (int i = 0; i < 1; i++)
        {
            Instantiate(Weapon[i], gameObject.transform.position, Quaternion.identity);
        }

    }

    private void Update()
    {
        Weapon[0].transform.Translate(0.00f, LaserSpeed, 0.00f * Time.deltaTime);
    }

Thank you too all of you for your replies. Have a great day. :slight_smile:

Yeah, I see. Weapon[0] is not a game object, but a prefab. It is sort of a “template” for a game object. You cannot move it. There is only one template, but might be hundred objects on a scene that made of this template. Thus, you are supposed to instantiate the game object and then save it in a variable. This variable will be a link to the specific object on a scene.

    LaserSpeed  = 5.00f;
    GameObject[] objs = new GameObject[amount]; // I do not know how many prefabs you have, or how many objects you want to instantiate

    private void Awake()
    {
        for (int i = 0; i < 1; i++)
        {
            objs[i] = (GameObject)Instantiate(Weapon[i], gameObject.transform.position, Quaternion.identity);
        }
    }
    private void Update()
    {
        objs[0].transform.Translate(0.00f, LaserSpeed, 0.00f * Time.deltaTime);
    }

That should be:

    private GameObject[] objs;
    private void Awake()
    {
        objs = new GameObject[Weapon.Length];
        ...
    }

So you don’t have to change the length of objs manually when you change the length of the weapons array. Otherwise the advice is solid!