- Home /
Enemy shooting at player Unity2D
I'm trying to make it so that my enemy AI can shoot at and target the player in a 2D game. I get the errors:
Assets/Meep/Dialogues/enemyshoot.cs(21,35): error CS0118: enemyshoot.Projectile' is a
field' but a 'type' was expected
Assets/Meep/Dialogues/enemyshoot.cs(22,28): error CS1061: Type object' does not contain a definition for
instantiate' and no extension method instantiate' of type
object' could be found (are you missing a using directive or an assembly reference?)
This is my current script:
using UnityEngine;
using System.Collections;
public class enemyshoot : MonoBehaviour {
public GameObject _controller;
private Vector2 _direction;
private Vector2 _startPosition;
private float _canFireIn;
public GameObject Projectile;
public void Start (){
//_controller = GetComponent<>();
_direction = new Vector2(-1, 0);
_startPosition = transform.position;
}
public void Update() {
if ((_canFireIn -= Time.deltaTime) > 0)
return;
var raycast = Physics2D.Raycast(transform.position, _direction, 10, 1 << LayerMask.NameToLayer("Player"));
if (!raycast)
return;
var projectile = (Projectile) Instantiate(Projectile, transform.position, transform.rotation);
projectile.instantiate(gameObject, _direction, _controller.Velocity);
//_canFireIn = FireRate;
}
}
Answer by MolochSim · Dec 09, 2014 at 08:43 PM
The problem is that you have a class called Projectile and therefore cannot declare a variable with the name Projectile. Simply changing that to projectile wiwthout the capital P will fix the first error. In line 21 and 9.
I can't tell if you have an instantiate method iside the Projectile class. But from the error, you seem not to have one. What are you trying to achieve in line 22?
I'm trying to make it so that the projectile appears and is launched towards the player, however I'm not entirely sure how to go about doing that.
First do what I said in my answer. I assume you are using a prefab as it is the most common way of approaching projectiles. If so, delete line 22. Add a movement script to the prefab, that will make it advance in its trajectory, or track the target you set for it. The movement should probably reside within a script attached to the projectile prefab in the Update function.
Your answer
![](https://koobas.hobune.stream/wayback/20220613173641im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
projectile formula 1 Answer
Calculate parabolic initial velocity and angle? 0 Answers
Enemy shooting player driving me crazy! 2 Answers
How do I apply damage to the enemy ai with projectile 0 Answers
Move projectile in a specific direction 0 Answers