I’m trying to instantiate an object once the left mouse button is clicked and I want the location of that object to be the location of where the cursor was when the mouse button was clicked. Here’s the code I’m using.
The problem is that object that is instantiated doesn’t take in the coordinates of the Vector3, I think it’s spawning it’s original transform coordinates first and not spawning the Vector3 coordinates I am trying to pass in.
So my question is:
How do I pass in the transform coordinates of the Vector3 I have created and pass those coordinates into the instantiated object.
The coordinates are right it’s just the position that is wrong.
Okay, that’s a little odd, how you got that working. I didn’t realize you could set it that way on the to be instantiated game object.
Instantiate returns an ‘object’.
You can either pass the position to the Instantiate method, it looks like: Instantiate(object, position, rotation)
or you can do:
Actually both snippets suffer from the same problem. The second script appears to work because you manipulate the object that you’re about to be copy/instantiate, hence the copy gets the same transfrom values as well.
You certainly want to either use the overload of Instantiate (like recommend by @methos5k ) that takes position and rotation or access the actual instance that you’ve created (which will be returned by Instantiate):
Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// 1) overload of Instantiate
Instantiate(TankLocationRadius, worldPos, Quaternion.identity);
//or 2) reference the instantiated obj that is returned by Instantiate (called obj in this example)
var obj = Instantiate(TankLocationRadius);
obj.position = worldPos;
// or 3) the shorter version
Instantiate(TankLocationRadius).position = worldPos;
That’s interesting. I knew that if you instantiated an in-game object, the new one would get its position and so forth, but for some reason I was under the belief that instantiated (assets) would get Vector3.zero. That’s probably something I ‘guessed’ a while ago, and never really updated in my head.
Good to know. heh.