using a setter from a different script

I am trying to remake space invaders in unity. I have a ship(made of a base and a cannon) and bullet prefab. When the space bar is pressed the fire method is activated.

    public void firing(){
        if ((Input.GetAxis ("Jump")) > 0 && (canShoot == true)) {
            setShoot (false);
            Instantiate(shot,new Vector3(cannon.transform.position.x,cannon.transform.position.y,cannon.transform.position.z),Quaternion.identity);
        }
    }

and the setShoot method is shown below

    public void setShoot(bool state){
        canShoot = state;
    }

The bullet will fire to the top of the screen and use the setShoot method to allow the player to shoot again.

    public int speed;

    public GameObject player;

    void Update () {
        transform.position += Vector3.up * speed * Time.deltaTime;
        if (transform.position.y >= 5.2) {
            player.GetComponent<PlayerControls>().setShoot(true);
            Destroy(this);
        }
    }

The issue i’m finding is that the player can not shoot again ( I have dragged the prefab for the ship into the prefab of the bullet). The method is called again but the ships value for canShoot = false. Am I missing something?

Also , please say if you need any more information, i’m new to asking these sort of programming questions.

First, how is player getting set on your bullets? Are you sure it’s getting set properly?

You may consider having a collider at the edge of your screen that is a trigger so when the bullet hits it, that triggers the reset of the bool instead.

Also, is your if statement triggering properly?

he said it himself… he’s setting prefab to prefab. so spawned bullets are referencing the prefab project asset of his ship, and not in the in-scene instance of his ship.

try this code:

 public void firing(){
        if ((Input.GetAxis ("Jump")) > 0 && (canShoot == true)) {
            setShoot (false);
            GameObject bulletGo = Instantiate(shot,cannon.transform.position,Quaternion.identity) as GameObject;

            var bulletScript = bulletGo.GetComponent<Bullet>(); //or whatever your Bullet class is named
            bulletScript.player = gameObject;
        }
    }
2 Likes