Unity не видит ничего противоречащегоC#

Место общения программистов C#
Ответить
Anonymous
 Unity не видит ничего противоречащего

Сообщение Anonymous »

Я делаю простую 2D-игру в Unity. Несмотря на то, что я следую инструкциям и проверяю документацию, мои коллизии не обнаруживаются должным образом. Я пробовал различные подходы, в том числе использование OnCollisionEnter2D и OnTriggerEnter2D, но, похоже, ничего не работает. Я также проверил коллайдеры, компоненты Rigidbody2D и настройки слоев, но все еще застрял.
Проблема в том, что тело с коллайдером 70x70 полностью находится буквально в середине 10 Коллайдер раз больше Unity ничего не видит. Также нет других коллайдеров, которые могут столкнуться с меньшими.
Я реализовал скрипт, который должен обнаруживать столкновения между объектом игрока и несколькими целевыми объектами (дырками). Я ожидал, что метод OnCollisionEnter2D будет вызываться, когда игрок сталкивается с этими целями, и соответственно начисляться очки. Однако обнаружение столкновений вообще не срабатывает. Я добавил журналы отладки, чтобы отслеживать ход выполнения кода, но журналы показывают, что методы столкновений никогда не срабатывают.
Я также создал простую тестовую сцену с базовыми фигурами, которые можно изолировать проблему, но даже это не помогает. Что мне попробовать дальше?
Вот мой код

Код: Выделить всё

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class Chapter1Manager : MonoBehaviour
{
public Image crosshair; // Crosshair for aiming
public Image[] holes = new Image[10];   // Array to hold hole prefabs
public Canvas canvas;  // Reference to the Canvas
public int bullets = 10; // Number of bullets available
public TextMeshProUGUI bulletsCount; // UI element to display bullet count
public Image blue; // Reference to the blue object
public int points = 0; // Player's score
public TextMeshProUGUI pointsText; // UI element to display points
public int toSend = 0; // Index to track which hole to send next

void Start()
{
// Initialize the bullet count display
bulletsCount.text = bullets.ToString();

// Find all GameObjects with the tag "hole" and store them in the holes array
GameObject[] foundHoles = GameObject.FindGameObjectsWithTag("hole");
Debug.Log("Found " + foundHoles.Length + " holes.");

// Assign found hole objects to the holes array
for (int i = 0; i < foundHoles.Length && i < holes.Length; i++)
{
holes[i] = foundHoles[i].GetComponent();
Debug.Log("Assigned hole: " + holes[i].gameObject.name);
}
}

void Update()
{
// Update the points display
pointsText.text = "Points: " + points.ToString();

// Check if there are bullets left
if (bullets > 0)
{
// Check for space key press to shoot
if (Input.GetKeyDown(KeyCode.Space))
{
// Ensure we have holes left to send
if (toSend < holes.Length) // Check if toSend is in range
{
// Set the position of the current hole to the position of the crosshair
holes[toSend].gameObject.transform.position = crosshair.transform.position;

// Increment the index for the next hole and decrement the bullet count
toSend++;
bullets--;
bulletsCount.text = bullets.ToString(); // Update the bullet count display
Debug.Log("Shot fired! Bullets left: " + bullets);
}
else
{
Debug.Log("No more holes to send.");
}
}
}
}

private void OnCollisionEnter2D(Collision2D collision)
{
// Log the name of the colliding object
Debug.Log("Collision detected with: " + collision.gameObject.name);

// Check if the collision is with the last hole sent or the blue object
if (toSend > 0 && (collision.gameObject == holes[toSend - 1].gameObject || collision.gameObject == blue.gameObject))
{
points += 10; // Increment points for a successful hit
Debug.Log("Hit! Points: " + points);
}
}
}
Также здесь находятся мои игровые объекты strictBodys и BoxColliders
Синий(из скрипта, первый объект взаимодействия дыра(из скрипта, второй объект взаимодействия

Подробнее здесь: https://stackoverflow.com/questions/792 ... -colliding
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»