- Home /
How to add a script to a object in unity
Hello Unity Community! I would like to ask you guys how do I add a script to an object? I am trying to add a gun script to a Gatling gun. I think I have found a script that could work But. I have tried to add scripts to an object before and I couldn't get my game to play cause there was a Error. Took me a while to figure out on how to remove the script (Still not quite sure on how I did it) So could you guys Link a video on how to add a script to a gun? and Do you guys think that you could test out this script I found and tell me if it works? This is the video on where I got the script from http://www.youtube.com/watch?v=yDS4Bf0ZKLA and this is the script. I don't know java scripting AT ALL. So please community, Help me and ill put your names in the credits saying that you help me out :D
var bulletTex : GameObject[]; // creates an array to use random textures of bullet holes
var power : int = 10; //provides power to our raycast that can affect our rigidbody components
var fireRate : float = 0.5;
private var nextFire : float = 0.0;
var gunShot : AudioClip;
function Update () {
Fire ();
}
function Fire () {
if(Input.GetButton("Fire1") && Time.time > nextFire) {
nextFire = Time.time + fireRate;
AudioSource.PlayClipAtPoint(gunShot, transform.position, 1);
ForceFire();
}
}
function ForceFire () {
var fwd = transform.TransformDirection(Vector3.forward); //casts our raycast in the forward direction
var hit : RaycastHit;
Debug.DrawRay(transform.position, fwd * 10, Color.green); //drays our raycast and gives it a green color and a length of 10 meters
if(Input.GetButton("Fire1") && Physics.Raycast(transform.position, fwd, hit, 10)){ //when we left click and our raycast hits something
Instantiate(bulletTex[Random.Range(0,3)], hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal)); //then we'll instantiate a random bullet hole texture from our array and apply it where we click and adjust
// the position and rotation of textures to match the object being hit
if (hit.rigidbody !=null)
hit.rigidbody.AddForceAtPosition(fwd * power, hit.point); //applies a force to a rigidbody when we click on it. Multiples our forward raycast times our power variable at the position we click
}
}
Answer by MauMaGau · Oct 09, 2013 at 07:22 PM
Hi Batman, welcome to Unity. Sounds like you're pretty new to the whole thing, so it'd be worth your time learning the basics - Unity have made some great bitesize tutorial vids that are really good for getting you up and running. http://www.youtube.com/user/Unity3D/videos?sort=dd&view=1&shelf_index=0
Your answer
Follow this Question
Related Questions
Shot Gun Script? And can I make the graphics retro? Need Help Please. 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
please help me with my script 2 Answers
Gui Skin not showing 0 Answers
AI enemy scripting help 1 Answer