Home > Software engineering >  Collision detection for individual objects in a list Unity3D
Collision detection for individual objects in a list Unity3D

Time:01-29

I want to have it so that a single game object from a list is destroyed when it hits the ground. So far I am able to spawn random prefabs in set spawn locations in the scene successfully, but I am having trouble implementing the collision detection for when they fall to the ground. I have tried both raycasting and OnCollisionEnter but neither is working, the collision is not being detected. I am missing something but not sure what. Below is my attempt with OnCollisionEnter:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectSpawner : MonoBehaviour
{
    public List<GameObject> prefabObjects;
    public List<GameObject> locations;
    public List<GameObject> spawnedObjects;

    void Start()
    {
        //create empty list of spawned objects
        spawnedObjects = new List<GameObject>();

        SpawnObject(RandomObjects());
    }
    // Update is called once per frame
    void Update()
    {

    }

    void SpawnObject(GameObject obj)
    {
        GameObject newObject = Instantiate(obj, transform.position, Quaternion.identity );

        spawnedObjects.Add(newObject);
    }

     GameObject RandomObjects()
     {

        int rand = Random.Range(0, prefabObjects.Count);
            
        return prefabObjects[rand];

     }

    void OnCollisionEnter(Collision collision)
    {
        for (var i = 0; i < spawnedObjects.Count; i  ){
            GameObject obj = spawnedObjects[i];

            if (collision.collider.tag == "Ground"){
                Debug.Log("Hit ground");
                spawnedObjects.Remove(obj);
                Destroy(obj);
            }
        }
    }

CodePudding user response:

Your void OnCollisionEnter(Collision collision) method is in the wrong place, you dont want the ObjectSpawner itself to collide but the instancianted obj's. Place a new script on your prefabs and implement OnCollisionEnter there. For the method to trigger, be sure to set up colliders and rigidbodies correctly. Your prefabs and the ground should have colliders and either one of these a non-kinematic rigidbody too.

  • Related