How do I change the transform of a clone object

I’m trying to change the transform of an object I’ve just instantiated using the following:

public GameObject marker;
public float maxLength;

newVector = Vector2.ClampMagnitude(diffVector, maxLength);
Instantiate(marker, newVector, transform.rotation);

newVector = Vector2.ClampMagnitude(diffVector, maxLength);
marker.gameObject.transform.position = newVector;
Debug.Log("Marker position = " + marker.gameObject.transform.position);

The diffVector is the difference between two objects that I want to track. There is other code around each block above but these are the pertinent parts.

I use the Debug.log to see that the marker.gameObject.position.transform is changing correctly, but the actual game object marker(clone) isn’t.

My guess is because its a clone but I don’t know how to reference them in the script.

Any help would be appreciated.

1 Answer

1

Instantiate returns a reference to the clone. You’ll need to capture that reference and use it to modify the clone’s transform.

You can see example code in the scripting docs for reference:

public class ExampleClass : MonoBehaviour {
    public Rigidbody projectile;
    void Update() {
        if (Input.GetButtonDown("Fire1")) {
            Rigidbody clone;
            clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
            clone.velocity = transform.TransformDirection(Vector3.forward * 10);
        }
    }
}

Thanks, I had looked at that I thought I'd tried it and it didn't work, but I think I had other problems with the code at the time, works fine now.

Why not flag rutter's answer as accepted then :)