- Home /
Assigning found enemy to target variable
Hello,
The following code is used to see if there is an enemy between the lines. If there is, the boolean will become "true". But how can I assign the found enemy to a variable (public GameObject)?
enemyInRange = Physics2D.Linecast(rangeStart.position, RangeEnd.position, 1 << Layermask.NameToLayer("Enemy"));
So if there is an enemy and I would have a variable public GameObject target; how could I assign the enemy in the way to that variable?
Answer by robertbu · May 03, 2014 at 02:39 PM
How about:
if (enemyInRange != null && enemyInRange.collider != null) {
someBool = true;
someGameObject = enemyInRange.collider.gameObject;
}
enemyInRange is a bool at the moment, so I believe this wouldn't work. Thus I have the GameObject target variable for the enemy in the range.
Answer by Pyrian · May 03, 2014 at 04:09 PM
Physics2D.Linecast returns a RaycastHit2D. I'm a bit surprised you CAN assign that to a Boolean, but you certainly shouldn't if you want to know what is hit. Instead, assign it to a RaycastHit2D, then go through that to get the GameObject.
RaycastHit2D enemyInRange = Physics2D.Linecast(rangeStart.position, RangeEnd.position, 1 << Layermask.NameToLayer("Enemy"));
if (enemyInRange != null) {
GameObject EnemyHit = enemyInRange.rigidbody.gameObject;
}
I tried several different ways to do that and always got an error:
"Cannot implicitly convert type `bool' to `UnityEngine.RaycastHit2D"
using UnityEngine;
using System.Collections;
public class Shoot : $$anonymous$$onoBehaviour {
public Transform rangeEnd;
public GameObject enemyHit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
RaycastHit2D hit = Physics2D.Raycast(transform.position, rangeEnd.position);
if(hit != null) {
}
}
}
That's all at the moment. What it should do after finding the target, is to deal damage to it if player presses $$anonymous$$ouse0 (if it is still in range).
Oh, I see. You need to just take out the "!= null", you can simply test "if (hit)".
Your answer
![](https://koobas.hobune.stream/wayback/20220613144146im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I assign a prefab to a variable with a script? 1 Answer
Multiple Cars not working 1 Answer
unity2d issue with linecasts. 1 Answer
Distribute terrain in zones 3 Answers