JRK
JRK

Reputation: 23

how can i access local variable out of a block

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour {

    public GameObject player;
    public GameObject arrow;
    private Vector3 a;
    private float angle;
    private Rigidbody2D rb2D;

    void Start()
    {

    }

    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            a = Input.mousePosition;
            Vector2 difference = a - player.transform.position;

            GameObject Aprefab = Instantiate(arrow) as GameObject;
            rb2D  = Aprefab.GetComponent<Rigidbody2D>();
            rb2D.AddForce(difference * 0.02f, ForceMode2D.Impulse);
        }
        angle = Mathf.Atan2(rb2D.velocity.y, rb2D.velocity.x);
        Aprefab.transform.localEulerAngles = new Vector3(0, 0, (angle * 180) / Mathf.PI);
    }
}

Currently, I am making an arrow shooter. I want to set arrow heading continuously while flying. so I need to access "Aprefab" GameObject out of if block. but how?

Need some help

Upvotes: 0

Views: 70

Answers (1)

AKX
AKX

Reputation: 168913

To expand upon my comment: I've

  • refactored the shooting stuff into another function
  • added a list arrows to keep track of all the arrows fired (that Shoot() adds to)
  • made Update() iterate over all the arrows and update them

I don't have Unity at present, and this is dry-coded, so there might be some bugs. Also, you'll want to take care of cleaning stuff up from the arrows list at some point.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour {

    public GameObject player;
    private List<GameObject> arrows = new List<GameObject>();

    void Start()
    {

    }

    void Update () {
        if (Input.GetMouseButtonDown(0))
        {
             Shoot();
        }
        foreach(var arrow in arrows) {
            var rb2D = Aprefab.GetComponent<Rigidbody2D>();
            var angle = Mathf.Atan2(rb2D.velocity.y, rb2D.velocity.x);
            arrow.transform.localEulerAngles = new Vector3(0, 0, (angle * 180) / Mathf.PI);
        }
    }

    private void Shoot() {
        var a = Input.mousePosition;
        var difference = a - player.transform.position;
        var Aprefab = Instantiate(arrow) as GameObject;
        var rb2D = Aprefab.GetComponent<Rigidbody2D>();
        rb2D.AddForce(difference * 0.02f, ForceMode2D.Impulse);
        arrows.Add(Aprefab);
   }
}

Upvotes: 4

Related Questions