Hey everyone, I just started using Unity yesterday so please overlook my ignorance over the next few weeks
Basically, I have the following code that, after pressing the mouse, shoots a projectile from the camera to the mouse click’s location (ignore the “print” commands, they’re just bug testing) :
function Start () {
}
function Update () {
if (Input.GetButtonDown ("Fire1")) {
print("foobar");
var ray : Ray = camera.ScreenPointToRay (Input.mousePosition);
print(ray);
var sphere : GameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
print(sphere);
sphere.transform.position = ray.origin;
sphere.AddComponent("Rigidbody");
sphere.transform.localScale += Vector3(.5, .5, .5);
sphere.rigidbody.AddForce (ray.direction * 2000);
}
}
As it stands, I create a primitive sphere that shoots out and collides with various items. What I want, however, is to use a custom-made model (an arrow). After importing my arrow into Unity how do I change the shot object from being a sphere to being that arrow?
In the beginning of the script where you want to instantiate a prefab, write:
var prefabClone : GameObject;
The part of the script where you want to instantiate that prefab clone, write:
var arrow = Instantiate(prefabClone, transform.position, transform.rotation );
Attach the script to something. In my case, since I wanted to have an arrow shoot from my camera, so I attached it to my camera.
Open the GameObject with the attached script in the hierarchy tab. Look at its inspector on the right pane. Notice that if you expand the script area (in my case, the “shooter” script that I attached, you see an empty gameObject that is the variable you defined at the beginning of the script (in my case, “prefabClone”).
Assuming you have the prefab titled “prefabClone” already created in the Project tab, drag it from that tab to the inspector, on top of the empty GameObject in the script you created.
Congrats! You’re done! The only issue with my code is the local rotation - if the camera moves, the projectile still tries to orient to the previous camera viewing angle (if I turn around in-game, the arrow will appear to be oriented backwards as it fires forward).
My code:
var arrowshoot : GameObject;
/* one, two, skip a few methods */
function Update () {
if (Input.GetButtonDown (“Fire1”)) {
var ray : Ray = camera.ScreenPointToRay (Input.mousePosition);
print(ray);
var sphere = Instantiate(arrowshoot, transform.position, transform.rotation );
sphere.transform.position = ray.origin;
sphere.transform.localScale += Vector3(.5, .5, .5);
sphere.transform.localRotation.x = 1;
sphere.rigidbody.AddForce (ray.direction * 5000);
}
}