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:
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.
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:
Use List.RemoveAll()
to prune null
entries from the collection after any of your created objects have been Destroy()
ed.
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.