Kooth
March 10, 2015, 3:29pm
1
Hello !
I wan’t to instantiate a object and move it .
Actually doesn’t work : only a lot of my object spawn.
var cube : Transform;
function Update () {
var hit : RaycastHit;
// var mousePos : Vector3 = Input.mousePosition;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.GetKey(KeyCode.B)) {
if(Physics.Raycast(ray,hit, 8)) {
if(hit.transform.tag == "terrain" ){
Instantiate(cube,hit.point,Quaternion.identity);
cube.position = hit.point ;
}
}
}
thanks
A couple things…
You are using GetKey which will return true for every frame the key is pressed. You may want to use GetKeyDown or GetKeyUp depending on when you want the event to occur.
You are changing your prefab’s position, not the position of the Instantiated object.
GameObject obj = (GameObject)Instantiate (cube, hit.point, Quaternion.identity);
obj.transform.position = hit.point;
Kooth
March 10, 2015, 3:50pm
3
Hey!
Thank for reply !
But i have a problem i add
var obj : GameObject = Instantiate(cube,hit.point,Quaternion.identity);
but i have a error : Cannot convert ‘UnityEngine.Transform’ to ‘UnityEngine.GameObject’.
Sorry, I didn’t realize that you were using JavaScript and the cube was already a Transform.
Just change GameObject to Transform in the line you posted.
Kooth
March 10, 2015, 4:26pm
5
No it’s me !
I understand now but i don’t have what i wan’t .
if(Physics.Raycast(ray,hit, 8)) {
if(Input.GetKeyDown(KeyCode.B)) {
if(hit.transform.tag == "terrain" ){
var obj : Transform = Instantiate(cube,hit.point,Quaternion.identity);
//obj.position = hit.point ;
}
}
if(Input.GetKey(KeyCode.N)) {
obj.position = hit.point ;
}
}
I wan’t when i press B my object instantiates et when i press N my object move and follow my mouse.
Thanks.
Niekos
March 11, 2015, 8:52am
6
You could make the object get Input.mouseposition and when you press N set it’s position to your mouseposition.
Kiwasi
March 11, 2015, 9:55am
7
In JavaScript casting is done using as
var obj : Transform = Instantiate(cube,hit.point,Quaternion.identity) as Transform;
Kiwasi:
In JavaScript casting is done using as
var obj : Transform = Instantiate(cube,hit.point,Quaternion.identity) as Transform;
JavaScript and C# handle casting in the same way. You can also use ‘as’ in C#, just like you can use (Transform)Instantiate (bla) in JavaScript.
Kiwasi
March 11, 2015, 8:26pm
9
You can use unsafe casting in JavaScript? That’s good to know. I honestly don’t pay much attention to the language, I was under the impression it only did safe casting. In that case its better to do this unsafe, like so
var obj : Transform = (Transform)Instantiate(cube,hit.point,Quaternion.identity);