- Home /
how to only be able to shoot if an object is active
hi, ive been trying to have system in wich i could only shoot a projectile if my bow is active. I want the projectile to shoot from my main camera so i cant put the script under my bow. Any ideas how i could get it to work? Here is the script im using.
#pragma strict
var arrow : Rigidbody;
var arrowSpeed = 25;
function Start () {
}
function Update () {
if (Input.GetButtonDown("Fire1"))
{
var clone = Instantiate(arrow, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection(Vector3(0, 0, arrowSpeed));
}
}
Answer by Eno-Khaon · May 01, 2015 at 07:55 PM
I certainly don't see why you can't shoot from your camera using the bow as the trigger.
To give an example of a way of doing it:
// Camera script
var currentWeapon: GameObject; // Set this variable to be your bow or any other weapon you may equip. The currently-equipped weapon would use this slot.
function Update()
{
if(currentWeapon != null)
{
if(Input.GetButtonDown("Fire1"))
{
currentWeapon.GetComponent(WeaponScript).Fire(transform.position);
}
}
}
And...
// Weapon script
var projectile: GameObject; // renamed from arrow to be generic, in case more than just a bow is usable
var projectileSpeed: float = 25;
function Fire(camera: Transform)
{
var clone = Instantiate(projectile, camera.position, camera.rotation);
clone.GetComponent(Rigidbody).velocity = camera.transform.TransformDirection(Vector3(0, 0, projectileSpeed));
}
Edit: Made a small change for safety.
Answer by Addyarb · May 01, 2015 at 07:58 PM
Just do a simple check to see if your bow is activeInHierarchy.
Assuming you don't have a way (yet) to enable/disable your bow...
GameObject bow; //drag your bow into the inspector to here.
bool isActive; //A bool to control whether or not our bow is active.
void Update(){
if(Input.GetKeyDown(KeyCode.B)){ //if we press the B key..
isActive = !isActive; //Set the bool to the opposite of what is was.
SetWeaponActive(isActive); //Call our SetWeaponActive method with said bool.
}
//If we click AND our bow is active...
if(Input.GetMouseButton(0) && isActive){
//Fire your bow projectile here..
}
}
//Function to set the bow active or inactive based on our bool in
//the above update function.
void SetWeaponActive(bool myBool){
bow.SetActive(myBool);
}
Your answer
Follow this Question
Related Questions
Alternatives to GameObject.SetActive(...) 2 Answers
Toggling the light with lightmapping(baked and dynamic shadows) 1 Answer
How to Enable and Disable Prefabs -1 Answers
Why does Unity disable the Collider when I Destroy the Rigidbody? (2D) 1 Answer
How to change settings to a rigidbody when adding it to a gamobject? 2 Answers