I don’t want bullets to instantiate or come out of the gun without equipping the gun so yet again I added a Boolean to say if q is pressed (weapon equipped) AND fire button or left mouse click then instantiate and fire bullet
So in the PickingObjects script
var SpawnTo : Transform; //attaches an object to your character that you want the position of what you picked up to go to, so goes to my bulletspawn
var Object1 : Transform; //The object you want to translate and move
var dist = 5; //distance at which you can pick things up
private var isHolding = false;
var equipped : boolean = false;
function Update () {
if(Input.GetKeyDown(KeyCode.Q)){ //if you press 'q', q because closer to finger
if(Vector3.Distance(SpawnTo.position, Object1.position) < dist)
{
isHolding = !isHolding; //changes isHolding var from false to true
}
}
if(isHolding == true){
equipped = true;
Debug.Log("equipped should be true" + equipped);
Object1.rigidbody.useGravity = false; //sets gravity to not on so it doesn't just fall to the ground
Object1.parent = SpawnTo; //parents the object
Object1.transform.position = SpawnTo.transform.position; //sets transform position
Object1.transform.rotation = SpawnTo.transform.rotation; //sets rotation
}
else{ //if isHolding isn't true
SpawnTo.transform.DetachChildren(); //detach child (object) from hand
Object1.rigidbody.useGravity = true; //add the gravity back on so resets everything
equipped = false;
Debug.Log("equipped should be false" + equipped);
}
}
I initialized a Boolean named equipped, set is as false and set it as true when q is pressed and set it back to false again after it is dropped.
Now in the gunscript with the fire button click, I called in the variable from another script but I’m getting this error
var BulletSpawn : Transform;
var Bullet : GameObject;
var firesfx : AudioClip;
function Start () {
}
function Update () {
var Script : PickingObjects = GetComponent(PickingObjects);
if(Input.GetButtonDown("Fire1" Script.equipped == true)){
audio.PlayOneShot(firesfx);
Instantiate(Bullet ,BulletSpawn.transform.position , BulletSpawn.transform.rotation);
}
}
InvalidCastException: Cannot cast from source type to destination type.
gunscript.Update () (at Assets/Scripts/gunscript.js:17)
line 17
if(Input.GetButtonDown(“Fire1” Script.equipped == true)){
I am calling in the equipped boolean variable from another script using this code which is in the update function
(note if I put it anywhere else I get errors stating 'UnityException: You are not allowed to call this function when declaring a variable.
Move it to the line after without a variable declaration.
If you are using C# don’t use this function in the constructor or field initializers, Instead move initialization to the Awake or Start function.
gunscript…ctor () (at Assets/Scripts/gunscript.js:5)’
var Script : PickingObjects = GetComponent(PickingObjects);