Shoot where my character is facing.

Hi all!!

Im new with this tool and im making a 2d platformer game, where i can make my char shot lasers to where he is looking at.

This is the script for him to shoot:

using UnityEngine;
using System.Collections;

public class Dispara : MonoBehaviour {
public float fireRate = 5;
private float timeToFire = 0;
Transform Ojos;
public Transform Laser;

// Use this for initialization
void Awake()
{
Ojos = transform.FindChild(“Ojos”);

}
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if (Input.GetButton(“Fire1”) && Time.time> timeToFire)
{
timeToFire = Time.time + fireRate;
Shoot();
}
}

public void Shoot()
{
Instantiate(Laser, Ojos.position, Ojos.rotation);

}
}

This succesfully creates an instance of “Laser” wich i have created, and in laser i created a script wich on start would give it a speed:


using UnityEngine;
using System.Collections;

public class Laser : MonoBehaviour {

private Dispara direccionMira; //Here im accesing the script above.
private Vector2 direccion;
Transform coli;
void Awake()
{
direccionMira = new Dispara();//ERROR?
direccion = direccionMira.GetComponent().transform.forward;
coli = transform.FindChild(“Colision”);
}
void FixedUpdate()
{

coli.GetComponent().velocity = direccionMira.GetComponent().transform.forward * 6;

Invoke(“Destruir”,5);

}

void Destruir()
{
Destroy(gameObject,2);

}

}


There are 2 problems with this, it tells me first that i can create a “new” monobehaviour instance of class Dispara.

And bullet is not going to where the character is facing.

Please use code tags when posting snippets of code: Using code tags properly - Unity Engine - Unity Discussions

To address one point in your post:
MonoBehaviours cannot be created using the “new” keyword. They are Components and must be added to a GameObject.

You can either create a new GameObject and add the component, or make a prefab with the component already added, then Instantiate the prefab.

So without creating the prefab and using Instantiate, you would have to do this:

private Dispara direccionMira; //Here im accesing the script above.
private Vector2 direccion;
Transform coli;
void Awake() {
    direccionMira = new GameObject("NewDisparaGameObject",typeof(Dispara)).GetComponent<Dispara>();
    direccion = direccionMira.transform.forward; // note: you can get transform directly from any monobehaviour or gameobject
    coli = transform.FindChild("Colision");
}