Answer the question
In order to leave comments, you need to log in
Raycast unity2D does not find the object, what should I do?
I want to create a game where enemies spawn and when you click on them they are destroyed.
top view
I was told that you can use Raycast for this, I tried to use it, but nothing happens when I click on the enemies, although I wrote destroy
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Hitenemy : MonoBehaviour
{
public GameObject man;
GameObject enemy;
public Text score;
public int count = 0;
void Start()
{
StartCoroutine(Spawn());
}
IEnumerator Spawn()
{
while (true)
{
man.transform.position = new Vector2(Random.Range(-2.21f, 2.195f), Random.Range(-4.354f, 2.498f));
enemy= Instantiate(man);
yield return new WaitForSeconds(1.5f);
// Destroy(enemy);
// yield return new WaitForSeconds(1.5f);
}
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000,LayerMask.GetMask("enemi")))
{
Destroy(enemy);
}
}
private void OnMouseDown()
{
enemy=GameObject.FindWithTag("Player");
Destroy(enemy);
count++;
score.text = count.ToString();
}
}
Answer the question
In order to leave comments, you need to log in
let's try step by step. systematize all your past questions and attempts.
I would advise you to do it from scratch, so that it is "clean and clear" and without regard to past attempts and confusion.
- the main object will be in the scene. hit tester and object creator.
- objects are instantiated even through an infinite loop in the corontina (although, as for me, a timer on Update would be better, but I think it doesn’t matter here)
- hit check on the object - on Update via Raycast
now to trifles.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question