0
\$\begingroup\$

In Unity3D, if I place a C # script including transform.Translate on an object "A" in the hierarchy, it animates the translation of this object A.

How in C# can I apply that transform.Translate effect onto another object defined in the script itself?

I want to write a script similar to this:

using UnityEngine;
using System.Collections;

public class Create_Objects : MonoBehaviour {

    public float moveSpeed = 2f;
    public Transform otherObject;

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Q))
        {
            GameObject Object1 = new GameObject ("Object1");
        }
        otherObject.Translate (Time.deltaTime * moveSpeed, 0, Time.deltaTime * moveSpeed);
    }
}

But somehow I want that otherObject that I'm translating to refer to the Object1 I created when the user pressed "Q".

Thanks DMGregory for your last code!... and finally, same as before but the objects are created and translated from position of each previous object creates.

What is the new C # code?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

This is a very basic C# syntax question. If you find this aspect of the language is unclear to you, I highly recommend spending some more time on beginner tutorials to learn these fundamentals inside and out.

We can modify your example script to do what you describe like so:

public class Create_Objects : MonoBehaviour {

    public float moveSpeed = 2f;
    // Create a private variable that can store a handle to the object we created.
    Transform latestCreation;

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Q))
        {
            // When we create an object, cache a reference to its transform.
            var createdGameObject = new GameObject ("Object1");
            lastestCreation = createdGameObject.transform;
        }

        // If our latest creation is a valid game object
        // (already created and not yet destroyed)
        // then let's move it! Otherwise, skip this.
        if (latestCreation != null)
            latestCreation.Translate (new Vector3(1,0,1) * Time.deltaTime * moveSpeed);
    }

}

If you want to apply this translation to multiple created objects then:

  1. That should have been in your question in the first place. When you ask about a singular object only, you'll get answers about a singular object only, so take the time to ensure your question covers what you really want.

  2. We can replace our latestCreation with a collection of objects, and move all objects in that collection using standard iteration techniques like for or foreach loops.

Like so:

public class Create_Objects : MonoBehaviour {

    public float moveSpeed = 2f;
    // Create a private variable that can store a handle to the object we created.
    List<Transform> allCreations = new List<Transform>();

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Q))
        {
            // When we create an object, add its transform to our list.
            var createdGameObject = new GameObject ("Object" + allCreations.Count);
            allCreations.Add (createdGameObject.transform);
        }

        // Iterate over all created transforms and move them.
        foreach ( var creation in allCreations ) {
            if (creation != null)
                creation.Translate (new Vector3(1,0,1) * Time.deltaTime * moveSpeed);
        }
    }

}

You can further improve on this in a couple of ways:

  1. Use List.RemoveAll() to prune null entries from the collection after any of your created objects have been Destroy()ed.

  2. Split this into two scripts: one that only moves an object, and one that only creates objects. The creation script can attach the movement script to the objects it creates using AddComponent<NameOfYourMovementScript>() so they'll continue moving themselves independently without needing to be tracked in a separate list.

\$\endgroup\$
1
  • \$\begingroup\$ thanks GMGreogry ! that's it! but created objects that are no longer the last are no longer translated according to (1,0,1). Only the last object created is translated. How to modify your code so that all created objects are translated? \$\endgroup\$
    – kaloprat
    Commented Apr 1, 2019 at 10:54
0
\$\begingroup\$

I think you're asking how to have a script move a different object than the one it's attached to. The easiest way that I know how to do this is to declare a public variable at the top of the script, like public Transform otherObject;. You can then move that object by calling otherObjects.Translate() where you used to be calling transform.Translate().

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .