problem with overlapsphere
Im working on a tower defense like game where a turret should shoot at a given target, The aquiring of the target works, but I get a nullreferenceexception at line 26 at the addforce, I want to add a force to the bullet in the direction of the target. How should I do this?
using UnityEngine;
using System.Collections;
public class turret1 : MonoBehaviour {
float Range = 4f;
public Collider2D[] Targets;
public Transform spore;
Vector2 targetpos;
private float InstantiationTimer = .44f;
void Start () {
}
void Update () {
InstantiationTimer -= Time.deltaTime;
Collider2D[] Targets = Physics2D.OverlapCircleAll(transform.position, Range);
foreach (Collider2D hit in Targets){
if(hit.transform.tag == "enemy"){
targetpos = hit.gameObject.transform.position;
if (InstantiationTimer < 0) {
Rigidbody2D clone = Instantiate (spore, new Vector2 (transform.position.x, transform.position.y + .3f), Quaternion.identity) as Rigidbody2D;
clone.AddForce (new Vector2 (targetpos.x,targetpos.y));
InstantiationTimer = .44f;
}
}
}
}
}
Comment
Answer by OncaLupe · Nov 30, 2015 at 12:19 AM
The problem is your spore variable is of type Transform, but trying to convert it to Rigidbody2D via the Instantiate. You need to either change the variable type to Rigidbody2D, or do a GetComponent.
Transform clone = Instantiate(spore) as Transform;
clone.GetComponent<Rigidbody2D>().AddForce(Vector2.up * 50f);
Note: GetComponent is slow, so it'd be best to change the spore variable to Rigidbody2D.
Your answer
![](https://koobas.hobune.stream/wayback/20220612050802im_/https://answers.unity.com/themes/thub/images/avi.jpg)